text
stringlengths 8
6.88M
|
|---|
#include <iostream>
#include <string>
#include "queue.hpp"
int main(int argc, char* argv[])
{
std::string usage_str = "usage: problem NUMBER RULE\n\n"
"NUMBER\t the number of children in the game.\n"
"RULE\t the elimination rule\n";
// If the argument pattern isn't good, then print usage
if (argc != 3) {
std::cout << usage_str;
return 1;
}
int num = std::stoi(argv[1]);
int rule = std::stoi(argv[2]);
// Create the queue
cs202::queue<int> q;
for (int i = 0; i < num; i++) {
q.push(num - i);
}
// Simulate the problem
for (int i = 1; i < num; i++) {
for (int j = 1; j < rule; j++) {
q.push(q.pop());
}
q.pop();
}
std::cout << q.pop() << std::endl;
return 0;
}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int min(int a,int b)
{
return (a<b?a:b);
}
int max(int a,int b)
{
return (a>b?a:b);
}
void qsort_first(vector<int>& nums, int l , int r, long long& sum)
{
if (r <= l)
{
return;
}
int tmp;
int p = nums[l];
int i = l + 1;
for (int j=l+1;j<=r;j++)
{
if (nums[j] < p)
{
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
}
}
tmp = nums[l];
nums[l] = nums[i-1];
nums[i-1] = tmp;
qsort_first(nums,l,i-2, sum);
qsort_first(nums,i,r,sum);
sum += i-2 - l + 1 + r - i + 1;
}
void qsort_last(vector<int>& nums, int l , int r, long long& sum)
{
if (r <= l)
{
return;
}
int tmp;
tmp = nums[r];
nums[r] = nums[l];
nums[l] = tmp;
int p = nums[l];
int i = l + 1;
for (int j=l+1;j<=r;j++)
{
if (nums[j] < p)
{
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
}
}
tmp = nums[l];
nums[l] = nums[i-1];
nums[i-1] = tmp;
qsort_last(nums,l,i-2, sum);
qsort_last(nums,i,r,sum);
sum += i-2 - l + 1 + r - i + 1;
}
void qsort_med(vector<int>& nums, int l , int r, long long& sum)
{
if (r <= l)
{
return;
}
int tmp;
int mid = l + ((r-l+1)/2 - (((r-l+1))%2==0?1:0));
int mn = min(min(nums[l],nums[mid]),nums[r]);
int mx = max(max(nums[l],nums[mid]),nums[r]);
int mid_index = l;
if(nums[l] != mn && nums[l] != mx)
mid_index = l;
else if(nums[mid] != mn && nums[mid] != mx)
mid_index = mid;
else if(nums[r] != mn && nums[r] != mx)
mid_index = r;
tmp = nums[l];
nums[l] = nums[mid_index];
nums[mid_index] = tmp;
int p = nums[l];
int i = l + 1;
for (int j=l+1;j<=r;j++)
{
if (nums[j] < p)
{
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
}
}
tmp = nums[l];
nums[l] = nums[i-1];
nums[i-1] = tmp;
qsort_med(nums,l,i-2, sum);
qsort_med(nums,i,r,sum);
sum += i-2 - l + 1 + r - i + 1;
}
void qsort(vector<int>& nums, int l , int r, long long& sum)
{
if (r <= l)
{
return;
}
int r_ind = l + rand() % (r - l + 1);
int tmp;
tmp = nums[r_ind];
nums[r_ind] = nums[l];
nums[l] = tmp;
int p = nums[l];
int i = l + 1;
for (int j=l+1;j<=r;j++)
{
if (nums[j] < p)
{
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
}
}
tmp = nums[l];
nums[l] = nums[i-1];
nums[i-1] = tmp;
qsort(nums,l,i-2, sum);
qsort(nums,i,r,sum);
sum += i-2 - l + 1 + r - i + 1;
}
int main(int argc, char** argv)
{
ifstream f;
f.open(argv[1]);
vector<int> nums;
string s;
while (getline(f,s))
{
nums.push_back(stoi(s));
}
f.close();
vector<int> nums1(nums);
vector<int> nums2(nums);
vector<int> nums3(nums);
long long sum = 0;
qsort_first(nums,0,nums.size()-1,sum);
cout<<sum<<"\n";
sum = 0;
qsort_last(nums1,0,nums.size()-1,sum);
cout<<sum<<"\n";
sum = 0;
qsort_med(nums2,0,nums.size()-1,sum);
cout<<sum<<"\n";
sum = 0;
qsort(nums3,0,nums.size()-1,sum);
cout<<sum<<"\n";
return 0;
}
|
/*
* Modification.cpp
*
* Created on: 27 mai 2014
* Author: florent
*/
#include "Modification.h"
namespace Calcul {
Modification::Modification(Action* ac, int tDep, int tArr): act(ac), tDepart(tDep), tArrive(tArr) {
// TODO Auto-generated constructor stub
}
Modification::~Modification() {
// TODO Auto-generated destructor stub
}
bool Modification::operator==(Modification &m)
{
bool b = false;
if (tDepart == m.tDepart && tArrive == m.tArrive)
if (act == m.act)
b = true;
return b;
}
} /* namespace Calcul */
|
#include<bits/stdc++.h>
#include"print.h"
using namespace std;
void bubbleSort()
{
string s;
cout<<"Enter the file name: ";
cin>>s;
ifstream f(s);
int n;
f>>n;
int a[n];
for(int i=0;i<n;i++)
{
f>>a[i];
}
f.close();
bool flag=1,check=1;
for(int j=n-1;flag;j--){
flag=0;
for(int i=0;i<j;i++)
{
if(a[i]>a[i+1]){
int c=a[i];a[i]=a[i+1];a[i+1]=c;
flag=1;
}
}
}
print(a,n);cout<<endl;
for(int i=0;i<n-1;i++)
{
if(a[i]>a[i+1]){check=0;}
}
if(check){cout<<"Correct";}else cout<<"Not correct";
};
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100005
#define INF 0x3f3f3f3f
#define DEVIATION 0.00000005
typedef long long LL;
struct BITree{
long long tree[MAXN+10];
void init(){
memset(tree,0,sizeof(tree));
}
int lowbit(int k){
return k&(-k);
}
void add(int k, int num){
while( k < MAXN ){
tree[k] += num;
k += lowbit(k);
}
}
long long sum(int k){
int res = 0;
while( k > 0 ){
res += tree[k];
k -= lowbit(k);
}
return res;
}
}BIT;
long long table[MAXN+10];
long long L[MAXN+10];
long long R[MAXN+10];
int main(int argc, char const *argv[])
{
int kase;
scanf("%d",&kase);
while( kase-- ){
int num;
scanf("%d",&num);
BIT.init();
memset(table,0,sizeof(table));
memset(L,0,sizeof(L));
memset(R,0,sizeof(R));
for(int i = 0 ; i < num ; i++ ){
scanf("%lld",&table[i]);
L[i] = BIT.sum(table[i]);
BIT.add(table[i],1);
}
BIT.init();
for(int i = num-1 ; i >= 0 ; i-- ){
R[i] = BIT.sum(table[i]);
BIT.add(table[i],1);
}
long long ans = 0;
for(int i = 0 ; i < num ; i++ )
ans += L[i]*(num-1-i-R[i]) + (i-L[i])*R[i];
printf("%lld\n",ans);
}
return 0;
}
|
#include <Poco/Logger.h>
#include "util/HavingThreadPool.h"
using namespace std;
using namespace Poco;
using namespace BeeeOn;
HavingThreadPool::HavingThreadPool():
m_minThreads(1),
m_maxThreads(16),
m_threadIdleTime(5 * Timespan::SECONDS)
{
}
HavingThreadPool::~HavingThreadPool()
{
}
void HavingThreadPool::setMinThreads(int min)
{
if (min < 0)
throw InvalidArgumentException("minThreads must be non-negative");
m_minThreads = min;
}
void HavingThreadPool::setMaxThreads(int max)
{
if (max < 0)
throw InvalidArgumentException("maxThreads must be non-negative");
m_maxThreads = max;
}
void HavingThreadPool::setThreadIdleTime(const Timespan &time)
{
if (time.totalSeconds() <= 0)
throw InvalidArgumentException("threadIdleTime must be at least 1 second");
m_threadIdleTime = time;
}
void HavingThreadPool::initPool()
{
if (m_pool.isNull()) {
logger().notice("creating thread pool min: "
+ to_string(m_minThreads)
+ " max: "
+ to_string(m_maxThreads),
__FILE__, __LINE__);
m_pool = new ThreadPool(
m_minThreads,
m_maxThreads,
m_threadIdleTime.totalSeconds()
);
}
}
ThreadPool &HavingThreadPool::pool()
{
initPool();
return *m_pool;
}
|
#include <iostream>
#include <stdlib.h>
#include "tinyxml2.h"
#include "backend/Day.h"
using namespace tinyxml2;
#ifndef XMLCheckResult
#define XMLCheckResult(a_eResult) if (a_eResult != XML_SUCCESS) { printf("Error: %i\n", a_eResult); return a_eResult; }
#endif
bool checkDate(const char* day = 0, const char* month = 0, const char* year = 0) {
XMLDocument xml_doc;
XMLError eResult = xml_doc.LoadFile("events.xml");
if (eResult != XML_SUCCESS) return false;
XMLElement* elementYear = xml_doc.FirstChildElement("year");
while (elementYear != nullptr && !(elementYear->Attribute("YID",year))){
elementYear->NextSibling("year");
if (elementYear == nullptr) return false;
}
XMLElement* elementMonth = elementYear->FirstChildElement("month");
while (elementMonth != nullptr && !(elementMonth->Attribute("MID",month))){
elementMonth = elementMonth->NextSibling("month");
if (elementMonth == nullptr) return false;
}
XMLElement* elementDay = elementMonth->FirstChildElement("day");
while (elementDay != nullptr && !(elementDay->Attribute("DID",day))){
elementDay = elementDay->NextSibling("day");
if (elementDay == nullptr) return false;
}
eResult = xml_doc.SaveFile("events.xml");
XMLCheckResult(eResult);
return true;
}
bool createDate(const char* day = 0, const char* month = 0, const char* year = 0) {
XMLDocument xml_doc;
XMLError eResult = xml_doc.LoadFile("events.xml");
if (eResult != XML_SUCCESS) return false;
int yearInt = atoi(year);
int monthInt = atoi(month);
int dayInt = atoi(day);
if (yearInt <= 0 || monthInt <= 0 || monthInt > 12 || dayInt <= 0 || dayInt > 31) {
return false;
}else if(checkDate(day,month,year)){
return true;
}else {
XMLElement * elementYear = xml_doc.NewElement("year");
elementYear->SetAttribute("YID",year);
xml_doc.InsertFirstChild(elementYear);
XMLElement * elementMonth = xml_doc.NewElement("month");
elementMonth->SetAttribute("MID",month)
elementYear->InsertEndChild(elementMonth);
XMLElement * elementDay = xml_doc.NewElement("day");
elementDay->SetAttribute("DID",day)
elementMonth->InsertEndChild(elementDay);
}
eResult = xml_doc.SaveFile("events.xml");
XMLCheckResult(eResult);
return true;
}
bool addEvent(const char* day = 0, const char* month = 0, const char* year = 0, const char* title = 0,
const char* description = 0, const char* startTime = 0, const char* duration = 0) {
XMLDocument xml_doc;
XMLError eResult = xml_doc.LoadFile("events.xml");
if (eResult != XML_SUCCESS) return false;
createDate(day,month,year);
XMLElement* elementYear = xml_doc.FirstChildElement("year");
XMLElement* elementMonth = elementYear->FirstChildElement("month");
XMLElement* elementDay = elementMonth->FirstChildElement("day");
XMLElement* elementEvent = elementDay->FirstChildElement("event");
int eventNum = elementDay->LastChildElement("event")->IntAttribute(EID);
eventNum += 1;
elementEvent->SetAttribute("EID",eventNum);
XMLElement* elementTit = xml_doc.NewElement("title");
elementTit->SetText(title);
elementEvent->InsertEndChild(elementTit);
XMLElement* elementDesc = xml_doc.NewElement("description");
elementDesc->SetText(description);
elementEvent->InsertEndChild(elementDesc);
XMLElement* elementST = xml_doc.NewElement("startTime");
elementST->SetText(startTime);
elementEvent->InsertEndChild(elementST);
XMLElement* elementDur = xml_doc.NewElement("duration");
elementDur->SetText(duration);
elementEvent->InsertEndChild(elementDur);
eResult = xml_doc.SaveFile("events.xml");
XMLCheckResult(eResult);
return true;
}
bool pullDay(const char* day = 0, const char* month = 0, const char* year = 0) {
XMLDocument xml_doc;
XMLError eResult = xml_doc.LoadFile("events.xml");
if (eResult != XML_SUCCESS) return false;
XMLElement* elementYear = xml_doc.FirstChildElement("year");
while (elementYear != nullptr && !(elementYear->Attribute("YID",year))){
elementYear->NextSibling("year");
if (elementYear == nullptr) return false;
}
XMLElement* elementMonth = elementYear->FirstChildElement("month");
while (elementMonth != nullptr && !(elementMonth->Attribute("MID",month))){
elementMonth = elementMonth->NextSibling("month");
if (elementMonth == nullptr) return false;
}
XMLElement* elementDay = elementMonth->FirstChildElement("day");
while (elementDay != nullptr && !(elementDay->Attribute("DID",day))){
elementDay = elementDay->NextSibling("day");
if (elementDay == nullptr) return false;
}
//start testing section
int eventCurr = elementDay->FirstChildElement("event")->IntAttribute("EID");
int eventLast = elementDay->LastChildElement("event")->IntAttribute("EID");
XMLElement* elementEventCurr = elementDay->FirstChildElement("event");
Day* day = new Day();
while(eventCurr != eventLast){
const char* title = elementEventCurr->FirstChildElement("title")->GetText();
const char* description = elementEventCurr->FirstChildElement("description")->GetText();
int startTime = elementEventCurr->FirstChildElement("startTime")->GetText();
int duration = elementEventCurr->FirstChildElement("duration")->GetText();
//add event to day
day->setEvent(title,description,startTime,duration);
//increment event
elementEventCurr = elementEventCurr->NextSibling("event");
}
//end testing section
eResult = xml_doc.SaveFile("events.xml");
XMLCheckResult(eResult);
return true;
}
void trial () {
}
|
#include "rotate_state_subscriber.h"
CRotateStateSubscriber::CRotateStateSubscriber() :
m_pOnDataAvailable(nullptr)
{
}
CRotateStateSubscriber::~CRotateStateSubscriber()
{
}
bool CRotateStateSubscriber::ValidData()
{
return (m_sampleInfo.valid_data == DDS_BOOLEAN_TRUE);
}
DataTypes::Uuid CRotateStateSubscriber::GetId()
{
return m_data.id;
}
DataTypes::Status CRotateStateSubscriber::GetStatus()
{
return m_data.status;
}
radians_per_second_t CRotateStateSubscriber::GetActualRate()
{
return (radians_per_second_t)m_data.actualRate;
}
radians_per_second_t CRotateStateSubscriber::GetMinRate()
{
return (radians_per_second_t)m_data.minRate;
}
radians_per_second_t CRotateStateSubscriber::GetMaxRate()
{
return (radians_per_second_t)m_data.maxRate;
}
radians_per_second_t CRotateStateSubscriber::GetTargetRate()
{
return (radians_per_second_t)m_data.targetRate;
}
bool CRotateStateSubscriber::Create(int32_t domain)
{
return TSubscriber::Create(domain,
nec::process::ROTATE_STATE,
"EdgeBaseLibrary",
"EdgeBaseProfile");
}
void CRotateStateSubscriber::OnDataAvailable(OnDataAvailableEvent event)
{
m_pOnDataAvailable = event;
}
void CRotateStateSubscriber::OnDataDisposed(OnDataDisposedEvent event)
{
m_pOnDataDisposed = event;
}
void CRotateStateSubscriber::OnLivelinessChanged(OnLivelinessChangedEvent event)
{
m_pOnLivelinessChanged = event;
}
void CRotateStateSubscriber::OnSubscriptionMatched(OnSubscriptionMatchedEvent event)
{
m_pOnSubscriptionMatched = event;
}
void CRotateStateSubscriber::DataAvailable(const nec::process::RotateState &data,
const DDS::SampleInfo &sampleInfo)
{
m_sampleInfo = sampleInfo;
if (sampleInfo.valid_data == DDS_BOOLEAN_TRUE)
{
m_data = data;
if (m_pOnDataAvailable != nullptr)
{
m_pOnDataAvailable();
}
}
}
void CRotateStateSubscriber::DataDisposed(const DDS::SampleInfo &sampleInfo)
{
LOG_INFO("Sample disposed");
m_sampleInfo = sampleInfo;
if (m_pOnDataDisposed != nullptr)
{
m_pOnDataDisposed(sampleInfo);
}
}
void CRotateStateSubscriber::LivelinessChanged(const DDS::LivelinessChangedStatus &status)
{
LOG_INFO("Liveliness lost");
if (m_pOnLivelinessChanged != nullptr)
{
m_pOnLivelinessChanged(status);
}
}
void CRotateStateSubscriber::SubscriptionMatched(const DDS::SubscriptionMatchedStatus &status)
{
LOG_INFO("Subscription matched");
if (m_pOnSubscriptionMatched != nullptr)
{
m_pOnSubscriptionMatched(status);
}
}
|
#include "Mat3.h"
namespace Move
{
Mat3::Mat3():
m00( 0.0f ), m01( 0.0f ), m02( 0.0f ), m10( 0.0f ), m11( 0.0f ), m12( 0.0f ), m20( 0.0f ), m21( 0.0f ), m22( 0.0f )
{}
Mat3::Mat3(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22):
m00( m00 ), m01( m01 ), m02( m02 ), m10( m10 ), m11( m11 ), m12( m12 ), m20( m20 ), m21( m21 ), m22( m22 )
{}
Vec3 operator*(const Vec3 &v, const Mat3 &m)
{
return Vec3(v.x*m.m00 + v.y*m.m01 + v.z*m.m02,
v.x*m.m10 + v.y*m.m11 + v.z*m.m12,
v.x*m.m20 + v.y*m.m21 + v.z*m.m22);
}
}
|
#include "RoomManager.h"
#include "PacketAccumulator.h"
#include "RelayServer.h"
static const long long TICKRATE = 30;
void RoomManager::createRoom(PacketAccumulator& packetAccumulator, std::array<char, HASH_LENGTH> room) {
const std::lock_guard<std::mutex> roomLock(m_roomMutex);
// clean up dead threads here just because its convenient
{
const std::lock_guard<std::mutex> completedLock(m_completedMutex);
for (std::array<char, HASH_LENGTH> completedRoom : m_completedThreads) {
m_roomThreads[completedRoom].join();
m_roomThreads.erase(completedRoom);
}
m_completedThreads.clear();
}
if (contains(m_roomThreads, room)) {
return;
}
m_roomThreads[room] = std::thread([this, &packetAccumulator, room] {
std::vector<ReceivedConnection> connections;
std::vector<ReceivedPacket> packets;
std::vector<RelayThreadController> controllers;
while (packetAccumulator.hasRoom(room)) {
auto startTime = std::chrono::high_resolution_clock::now();
// do stuff
// for now just send back all packets? no filtering?
packetAccumulator.getPackets(packets, room);
if (!packets.empty()) {
packetAccumulator.getConnections(connections, room);
controllers.clear();
for (auto& connection : connections) {
controllers.emplace_back(m_threadPool.run([&connection, &packets]() {
std::vector<uint8_t> bytes;
int byteCount = 0;
for (auto& packet : packets) {
if (packet.identifier == connection.identifier) {
continue;
}
byteCount += packet.length;
}
bytes.resize(byteCount);
int currentIndex = 0;
for (auto& packet : packets) {
if (packet.identifier == connection.identifier) {
continue;
}
std::memcpy(bytes.data() + currentIndex, packet.bytes.data(), packet.length);
currentIndex += packet.length;
}
RelayServer::send(connection.handle, bytes.data(), bytes.size());
}));
}
for (RelayThreadController& controller : controllers) {
controller.join();
}
}
auto endTime = std::chrono::high_resolution_clock::now();
long long duration = std::chrono::duration_cast<std::chrono::nanoseconds>(endTime - startTime).count();
long long delay = std::max(0LL, 1000000000LL / TICKRATE - duration);
std::this_thread::sleep_for(std::chrono::nanoseconds(delay));
}
// can you do this from within the thread that will be destroyed as a result of this action?
const std::lock_guard<std::mutex> completedLock(m_completedMutex);
m_completedThreads.emplace_back(room);
});
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "TestCharacter.h"
#include "Components/SkeletalMeshComponent.h"
#include "GameFramework/Actor.h" //framerworks
#include "Kismet/GameplayStatics.h" //gmaeplaystatics for restarting the game
// Sets default values
ATestCharacter::ATestCharacter()
{
// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
GetCapsuleComponent()->InitCapsuleSize(42.0f, 96.0f); //a pointer, also can change it in Unreal engine under CapsuleComponent
bUseControllerRotationPitch = false; //all these three will not allow the character to rotate instead it will allow the camera to rotate.
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
GetCharacterMovement()->bOrientRotationToMovement = true; //a pointer, allow the character to rotate in the direction it is moving.
GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); //(x, y, z) rotation rate, rate by wich we are going to rotate
GetCharacterMovement()->JumpZVelocity = 600.0f; //when jump the velocity will be 600
GetCharacterMovement()->AirControl = 0.2f; //how much we are going to control our charactor in air
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); //CreateDefaultSubobject is a type of USpringArmComponent, the name cameraboom is the name that will appear on the testcharacter_bp manu for USpringArmComponent
CameraBoom->SetupAttachment(RootComponent); //attach to rootcomponent, the rootcomponent in this case is capsulecomponent therefore cameraboom will become a child of the capsulecomponent.
CameraBoom->TargetArmLength = 300.0f; //how far away the camera(springArm) will be away from the robot(user).
CameraBoom->bUsePawnControlRotation = true; //rotate the arm base on the controller.
//inorder for us to test the rotation of the arm base on the controller we have to create a (camera).
FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName);//attach this camera to cameraboom, this is going to attach the camera at the end of the boom and let the boom adjust the match controller rotation of the camera.
FollowCamera->bUsePawnControlRotation = false; //the camera does not rotate relaltive to the arm.
bDead = false;
Power = 100.0f;
}
// Called when the game starts or when spawned
void ATestCharacter::BeginPlay()
{
Super::BeginPlay();
//bind the OnBeginOverlap with the component, if we dont bind that with the capsule component then which means we can not trigger it when we collided with a actor(game object).
GetCapsuleComponent()->OnComponentBeginOverlap.AddDynamic(this, &ATestCharacter::OnBeginOverlap);
if (Player_Power_Widget_Class != nullptr) //we are testing this because we want to make sure its not equal to the null pointer, the reason for this is because we might have not attach the (Player_Power_UI)health bar under (UI HUD)that we have created.
{
Player_Power_Widget = CreateWidget(GetWorld(), Player_Power_Widget_Class);
Player_Power_Widget->AddToViewport();
}
}
// Called every frame
void ATestCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime); //Tick is called every frame
Power -= DeltaTime * Power_Treshold; //subtract the power
if (Power <= 0)
{
if (!bDead)
{
bDead = true;
GetMesh()->SetSimulatePhysics(true);
FTimerHandle UnusedHandle;
GetWorldTimerManager().SetTimer(
UnusedHandle, this, &ATestCharacter::RestartGame, 3.0f, false);
/*this get worldtimermanager is goint to setTimer(set the timer), by using UnusedHandle(in the above, it is a parameter we need to pass inside of this(this class)),
<&ATestCharacter::Restart> is the function we need to excute after three seconds(3.0f), and false because we dont want to repeatedly call this funciton after three second. */
}
}
}
// Called to bind functionality to input
void ATestCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
//place move function after input to bind them
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); /*binding (turn) in (setting) under (input) in (Axis Mappings), (this) refering to this class(the function we are in right now), we are blinding it to (APawn-controllerYawInput) which allow us to contoll the yaw of the player(the yaw is the rotation of the player). (the yaw is under mesh in testcharacter_BP, in transform-rotation-Z(z is the yaw, which you can left click it and hold it then move left and right to see the difference)*/
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); //by blinding pitch and yaw, now you can move the camera of the character to watch where he is.
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); //blind a action and the name of the action is going to be jump, and we are going to bind the press and release of it., (ACharacter::Jump) is a function inside of the (character class) that we can use to jump.
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping);
/*all these are build in functions, (AddControllerYawInput) and (AddControllerPitchInput) are build in functions inside of APawn.
and (Jump) and (StopJumping) are also build in function but inside of ACharacter. because we inherited the character inside of the TestCharacter.h which mean we have also inherited all its funciton*/
/*now bind our move forward and move right
IMPORTANT- the name we create have to match to the name in the Unreal Engine project settings. EX: MoveForward=MoveForward*/
PlayerInputComponent->BindAxis("MoveForward", this, &ATestCharacter::MoveForward); //this is going to bind the moveforward action which is under (setting-input-axis mappings). so when we do that we will call the moveforward function.
PlayerInputComponent->BindAxis("MoveRight", this, &ATestCharacter::MoveRight);
}
void ATestCharacter::MoveForward(float Axis)
{
if (!bDead) //if my character is not dead then I am able to move the character.
{
const FRotator Rotation = Controller->GetControlRotation(); //create a constant
const FRotator YawRotation(0, Rotation.Yaw, 0); // getting the rotation to find out the forward direction.(x,y,z)-formate for the parameter
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); //calculate the forward. direction is the forward direction, we are passing the (YawRotation). this is going to calculate the forward direction of this vector.
AddMovementInput(Direction, Axis); //this Axis is this Axis(ATestCharacter::MoveForward(float Axis)).
}
}
void ATestCharacter::MoveRight(float Axis)
{
if (!bDead)
{
const FRotator Rotation = Controller->GetControlRotation(); //create a constant
const FRotator YawRotation(0, Rotation.Yaw, 0);
const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); //remember this is Y axis not X
AddMovementInput(Direction, Axis);
}
}
void ATestCharacter::RestartGame()
{
UGameplayStatics::OpenLevel(this, FName(*GetWorld()->GetName()), false);
//open the level inside of this(refering to this class) and get the world and name(getting the name of the world), we use Astrix(->) because we dealing with a pointer, and false.
}
void ATestCharacter::OnBeginOverlap(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweetResult)
{
if (OtherActor->ActorHasTag("Recharge")) //OtherActor is the OtherActor that we have collided with,recharge is the name of the tag
{
//UE_LOG(LogTemp, Warning, TEXT("COLLided with")); //use UE_LOG to print to the console. we are testing if the other actor has a tag recharged
Power += 10.0f; //to add to the power 10
if (Power > 100.0f)//test if the power is greater then 100.0f
Power = 100.0f; //not allowing the power to go above 100
OtherActor->Destroy(); //remove OtherActor
}
}
|
#pragma once
class SphericalBody {
private:
float m_mass; // In KG
float m_radius; // In KM
public:
SphericalBody(const float mass, const float radius)
: m_mass(mass), m_radius(radius) {}
inline float get_mass() const { return m_mass; }
inline float get_radius() const { return m_radius; }
inline void set_radius(const float radius) { m_radius = radius; }
inline void set_mass(const float mass) { m_mass = mass; }
};
|
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char *argv[])
{
vector< int > iv1(10,-1);
vector< int > iv2(3,9);
cout << "Before:" << endl
<< "iv1:" << iv1.size() << endl
<< "iv2:" << iv2.size() << endl;
//iv1 = iv2;
vector< int >::iterator iter1 = iv2.begin();
vector< int >::iterator iter2 = iv2.end();
iv1.assign(iter1,iter2);
cout << "After:" << endl
<< "iv1:" << iv1.size() << endl
<< "iv2:" << iv2.size() << endl;
return 0;
}
|
#include "texture_data.h"
#define STB_IMAGE_IMPLEMENTATION
#include <stb/stb_image.h>
TextureData::TextureData():
width(0), height(0), channels(0), size(0), pixels(nullptr)
{
}
TextureData::~TextureData()
{
if (pixels)
stbi_image_free(pixels);
}
stbi_uc* TextureData::load(const char* resource, int reqComp)
{
std::string filenameStr(resource);
const char* filename = filenameStr.c_str();
LOG("LOADING %s", filename);
#ifdef __ANDROID__
std::vector<char> bytes = FileManager::readFile(filenameStr);
pixels = stbi_load_from_memory((unsigned char *) bytes.data(), sizeof(char) * bytes.size(), &width, &height, &channels, reqComp);
#else
pixels = stbi_load(filename, &width, &height, &channels, reqComp);
#endif
LOG("AFTER LOAD");
size = width * height * reqComp;
if (!pixels || !size) {
char err[256];
sprintf(err, "TEXTURE ERROR reason: %s path:\"%s\" w:%d h:%d channels:%d reqComp:%d ", stbi_failure_reason(), filename, width, height, channels, reqComp);
throw std::runtime_error(err);
}
LOG("TEXTURE LOADED path:\"%s\" w: %d h: %d channels: %d reqComp: %d size: %d", filename, width, height, channels, reqComp, size);
return pixels;
}
int TextureData::getWidth() const
{
return width;
}
int TextureData::getHeight() const
{
return height;
}
int TextureData::getChannels() const
{
return channels;
}
stbi_uc* TextureData::getPixels()
{
return pixels;
}
uint64_t TextureData::getSize() const
{
return size;
}
TextureDesc::TextureDesc(const char* filename, int reqComp):
TextureDesc(std::string(filename), reqComp)
{
}
TextureDesc::TextureDesc(std::string filename, int reqComp):
filename(filename), reqComp(reqComp)
{
}
bool TextureDesc::operator==(const TextureDesc &other) const
{
return filename == other.filename && reqComp == other.reqComp;
}
|
// Sum of digits of Number using recursion
#include <iostream>
using namespace std;
int sum(int n)
{
if(n < 10) return n;
return n % 10 + sum(n/10);
}
int main()
{
int n;
cout<<"Enter a number ";
cin>>n;
cout<<"\nSum of digits ";
cout<<sum(n);
return 0;
}
|
#include "Particle.h"
std::vector < std::shared_ptr <Particle> > Particle::particle;
Particle::Particle(float a, float h, std::string name, float speed)
{
if (name == "BasicEnemy") teksture.loadFromFile("Images/Particles/BasicEnemy.png");
if (name == "EnemyTank") teksture.loadFromFile("Images/Particles/EnemyTank.png");
if (name == "EnemyFast") teksture.loadFromFile("Images/Particles/EnemyFast.png");
if (name == "BossBrown1") teksture.loadFromFile("Images/Particles/BossBrown1.png");
if (name == "BossBrown2") teksture.loadFromFile("Images/Particles/BossBrown2.png");
if (name == "BossBlack1") teksture.loadFromFile("Images/Particles/BossBlack1.png");
if (name == "BossBlack2") teksture.loadFromFile("Images/Particles/BossBlack2.png");
if (name == "BossGold") teksture.loadFromFile("Images/Particles/BossGold.png");
if (name == "BossBlue") teksture.loadFromFile("Images/Particles/BossBlue.png");
static bool firstTime = true;
if (firstTime)
{
srand(time(NULL));
firstTime = false;
}
sprite.setTexture(teksture);
sprite.setPosition(a, h);
//else
//{
// if (left) sprite.setPosition(a - 25, h);
// else sprite.setPosition(a + 25, h);
//}
timee = 0;
int los = rand() % 100;
int los2 = rand() % 100;
int los3 = rand() % 100;
this->speed.x = (los - 50) / 100.0f;
this->speed.y = (los2 - 50) / 100.0f;
rotation = (los3 - 50) / 100.0f;
float c = sqrt(pow(this->speed.x, 2) + pow(this->speed.y, 2));
this->speed.x /= c;
this->speed.y /= c;
this->speed.x *= (rand() % 100) / (float)100 * speed;
this->speed.y *= (rand() % 100) / (float)100 * speed;
}
void Particle::renderAll()
{
for (int i = particle.size() - 1; i >= 0; i--)
{
particle[i]->render();
}
}
void Particle::render()
{
Window::window.draw(sprite);
}
void Particle::updateAll()
{
for (int i = particle.size() - 1; i >= 0; i--)
{
particle[i]->update();
}
for (int i = particle.size() - 1; i >= 0; i--)
{
if (particle[i]->timee > 3000) particle.erase(particle.begin() + i);
}
}
void Particle::update()
{
timee += GameInfo::getDeltaTime();
sprite.move(speed.x * GameInfo::getDeltaTime() / 5.0, speed.y * GameInfo::getDeltaTime() / 5.0);
rotation *= 0.998;
speed.x *= 0.999;
speed.y *= 0.999;
sprite.rotate(rotation);
if(timee>2000) sprite.setColor(sf::Color(255, 255, 255, -(timee - 2000) / 4));
}
void Particle::addParticle(float a, float h, std::string name, int ammount, float speed)
{
for (int i = 0; i < ammount; i++)
{
Particle::particle.push_back(std::make_shared <Particle>(a, h, name, speed));
}
}
|
#include "field.hh"
#include <iostream>
#include "alpha-beta-ki.hh"
void print_position(pos p) {
std::cout << p.a << " " << p.b << std::endl;
}
void print_move(move m) {
std::cout << "move:" << std::endl;
print_position(m.a);
if(is_valid_pos(m.b))
print_position(m.b);
if(is_valid_pos(m.c))
print_position(m.c);
std::cout << m.dir << std::endl;
}
int main() {
field f = start_field();
std::list<move> list;
possible_moves(f, BLACK, &list);
for (std::list<move>::const_iterator iterator = list.begin(),
end = list.end(); iterator != end; ++iterator) {
print_move(*iterator);
}
}
|
#ifndef __UISPRITE_H__
#define __UISPRITE_H__
enum UIIMAGE { UI_BOTTOM, UI_ENDBACK, UI_ENDBOX,
UI_YES_NORMAL, UI_YES_OVER, UI_YES_CLICK,
UI_NO_NORMAL, UI_NO_OVER, UI_NO_CLICK,
UI_MAX };
class UISprite
{
D3DXVECTOR3 m_vPos;
D3DXVECTOR3 m_vRot;
D3DXVECTOR3 m_vScale;
D3DXMATRIX m_mTM;
D3DXMATRIX m_mScale, m_mRot, m_mTrans;
int m_iVtxCnt;
char m_strTextureName[256]; // 텍스쳐 이름
LPDIRECT3DTEXTURE9 m_pTexture;
bool m_bRenderTarget;
static LPDIRECT3DVERTEXBUFFER9 m_pVB;
static D3DFVF_XYZ_TEX1* m_pVertex;
static bool m_bFirst;
static int m_iCount;
public:
int m_Width, m_Height; // 텍스쳐 크기
public:
bool InitUI(int x, int y, char* name, D3DXCOLOR color=D3DXCOLOR(1,0,1,1));
bool InitUI(void);
void UpdateUI(float dTime);
void RenderUI(void);
void RenderAlphaUI(float alpha);
void ReleaseUI(void);
bool InitVTX(void);
public:
UISprite(bool renderTarget=false);
UISprite(LPDIRECT3DTEXTURE9 ppTexture);
virtual ~UISprite(void);
};
#endif
|
#include <iostream>
#include <forward_list>
#include <vector>
using namespace std;
/*
* Runs O(n)
*
*/
void partition(forward_list<int>& flist, int value) {
forward_list<int>::iterator prev {};
auto current = flist.begin();
bool seen_greater_than_or_equal_value = false;
while (current != flist.end()) {
if ((*current < value) && seen_greater_than_or_equal_value) {
flist.push_front(*current);
flist.erase_after(prev);
current = prev;
current++;
} else {
if (*current >= value) {
seen_greater_than_or_equal_value = true;
}
prev = current;
current++;
}
}
}
void print_list(const forward_list<int>& flist) {
for (auto elem : flist) {
cout << elem << ", ";
}
cout << endl;
}
void run_partition(forward_list<int> flist, int value) {
print_list(flist);
partition(flist, value);
print_list(flist);
cout << endl;
}
int main() {
run_partition({3, 5, 8, 5, 10, 2, 1}, 5);
run_partition({3, 5, 8, 5, 10, 2, 1}, 2);
run_partition({3, 5, 8, 5, 10, 2, 1}, 7);
}
|
#include <iostream>
#include <iterator>
using namespace std;
inline void _swap(int& num1, int& num2)
{
int temp;
temp = num1;
num1 = num2;
num2 = temp;
}
void InsertionSort(int* (&arr), int size)
{
int index;
for (int i = 1; i < size; i++)
{
index = i;
for (int j = i; j >= 0; j--)
{
if (arr[index] < arr[j])
{
_swap(arr[index], arr[j]);
index--;
}
}
}
}
int main(void)
{
ios::sync_with_stdio(false);
cout.tie(NULL); cin.tie(NULL);
int n;
int sum;
int* p;
cin >> n;
p = new int[n];
copy_n(istream_iterator<int>(cin), n, p);
InsertionSort(p, n);
for (int i = 1; i < n; i++)
p[i] += p[i - 1];
sum = 0;
for (int i = 0; i < n; i++)
sum += p[i];
cout << sum;
return 0;
}
|
#ifndef MYINPUTPANELCONTEXT_H
#define MYINPUTPANELCONTEXT_H
#include <QtGui/QInputContext>
class MyInputPanelContext : public QInputContext
{
Q_OBJECT
public:
MyInputPanelContext();
~MyInputPanelContext();
bool filterEvent(const QEvent* event);
QString identifierName();
QString language();
bool isComposing() const;
void reset();
/*
private slots:
void sendCharacter(QChar character);
private:
void updatePosition();
*/
// private:
// MyInputPanel *inputPanel;
};
#endif // MYINPUTPANELCONTEXT_H
|
#define COMPILATION_FAILED (-1)
RandomState rng;
Asset compile_progam(const char *file)
{
const char *source = read_entire_file(file);
if (!source)
{
Asset asset;
asset.shader.program = COMPILATION_FAILED;
return asset;
}
const char *preamble = "#version 130\n";
#define NUM_SHADER_PARTS 3
const char *vert_source[NUM_SHADER_PARTS] = {preamble, "#define VERT\n", source};
const char *frag_source[NUM_SHADER_PARTS] = {preamble, "#define FRAG\n", source};
GLuint vert_shader = glCreateShader(GL_VERTEX_SHADER);
GLuint frag_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vert_shader, NUM_SHADER_PARTS, vert_source, NULL);
glShaderSource(frag_shader, NUM_SHADER_PARTS, frag_source, NULL);
free_string(source);
#undef NUM_SHADER_PARTS
glCompileShader(vert_shader);
{
GLuint shader = vert_shader;
GLint is_compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &is_compiled);
if(is_compiled == GL_FALSE)
{
GLint max_length = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &max_length);
// The max_length includes the NULL character
GLchar *log = (GLchar *) push_memory(sizeof(char) * max_length);
glGetShaderInfoLog(shader, max_length, &max_length, log);
print("|| (VERT) GLSL %s\n", log);
pop_memory(log);
glDeleteShader(frag_shader);
glDeleteShader(vert_shader);
Asset asset;
asset.shader.program = COMPILATION_FAILED;
return asset;
}
}
glCompileShader(frag_shader);
{
GLuint shader = frag_shader;
GLint is_compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &is_compiled);
if(is_compiled == GL_FALSE)
{
GLint max_length = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &max_length);
// The max_length includes the NULL character
GLchar *log = (GLchar *) push_memory(sizeof(GLchar) * max_length);
glGetShaderInfoLog(shader, max_length, &max_length, log);
print("|| (FRAG) GLSL %s\n", log);
pop_memory(log);
glDeleteShader(frag_shader);
glDeleteShader(vert_shader);
Asset asset;
asset.shader.program = COMPILATION_FAILED;
return asset;
}
}
GLuint program = glCreateProgram();
glAttachShader(program, vert_shader);
glAttachShader(program, frag_shader);
glLinkProgram(program);
glDetachShader(program, vert_shader);
glDetachShader(program, frag_shader);
glDeleteShader(vert_shader);
glDeleteShader(frag_shader);
Asset asset;
asset.shader.program = program;
return asset;
}
void recompile_program(Asset *asset)
{
ASSERT(asset->type == AFT_SHADER);
Shader new_shader = compile_progam(asset->path).shader;
if (new_shader.program != (u64) COMPILATION_FAILED)
{
// Silent success
//print("|| Shader reloaded (%s@%d)\n", asset.path, asset.last_edit);
asset->shader = new_shader;
}
}
void destroy_program(Asset asset)
{
ASSERT(asset.type == AFT_SHADER);
}
Graphics initalize_graphics(AssetID id)
{
Graphics gfx;
gfx.shader_id = id;
rng = seed(8765456789);
f32 square[] = {
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f
};
glGenVertexArrays(1, &gfx.vertex_array);
glBindVertexArray(gfx.vertex_array);
glGenBuffers(1, &gfx.vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, gfx.vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(square), square, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, gfx.vertex_buffer);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void *) 0);
return gfx;
}
void destroy_graphics(Graphics *gfx)
{
glDeleteVertexArrays(1, &gfx->vertex_array);
glDeleteProgram(gfx->vertex_buffer);
}
void begin(Graphics *gfx, Camera *camera, Clock clock)
{
// TODO: This is slow, we should have a global context
// which caches the current state so we don't have to set
// it. But it's marginal.
glUseProgram(find_asset(gfx->shader_id).shader.program);
camera->shake_timer = maximum(0.0, camera->shake_timer - clock.delta);
f32 shake_strength = minimum(camera->shake_timer * camera->shake_timer, 1.0f);
shake_strength *= camera->shake_stress * camera->shake_stress;
Vec2 shake_position = camera->position + random_unit_vec2(&rng) * shake_strength;
f32 shake_rotation = camera->rotation + random_real_in_range(&rng, -0.2f, 0.2f) * shake_strength;
f32 shake_zoom = camera->zoom + random_real_in_range(&rng, -0.1f, 0.1f) * shake_strength;
// TODO: We should however cache this, so we don't have to write
// super long calls all the time.
GLuint program = find_asset(gfx->shader_id).shader.program;
glUseProgram(program);
#define u_loc(attr) (glGetUniformLocation(program, attr))
glUniform1f(u_loc("time"), clock.time);
glUniform1f(u_loc("aspect_ratio"), game.aspect_ratio);
glUniform2f(u_loc("camera_position"), shake_position.x, shake_position.y);
glUniform1f(u_loc("camera_rotation"), shake_rotation);
glUniform1f(u_loc("camera_zoom"), shake_zoom);
glClearColor(0.3f, 0.1f, 0.2f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void begin(Clock clock)
{
begin(game.context, game.camera, clock);
}
void draw_sprite(Graphics gfx, Texture texture, Rect region, Vec2 position, Vec2 scale, f32 rotation)
{
GLuint program = find_asset(gfx.shader_id).shader.program;
glUseProgram(program);
bind_texture(texture, 0);
glUniform2f(u_loc("min_uv"), region.min.x, region.min.y);
glUniform2f(u_loc("dim_uv"), region.dim.x, region.dim.y);
glUniform1i(u_loc("sprite_texture"), 0);
glUniform2f(u_loc("position"), position.x, position.y);
glUniform2f(u_loc("scale"), scale.x, scale.y);
glUniform1f(u_loc("rotation"), rotation);
glBindVertexArray(gfx.vertex_array);
glDrawArrays(GL_QUADS, 0, 4);
}
void draw_sprite(Texture texture, Rect region, Vec2 position, Vec2 scale, f32 rotation)
{
draw_sprite(*game.context, texture, region, position, scale, rotation);
}
void draw_sprite(Graphics gfx, Texture texture, Vec2 position, Vec2 scale, f32 rotation)
{
draw_sprite(gfx, texture, R(0, 0, 1, 1), position, scale, rotation);
}
void draw_sprite(Texture texture, Vec2 position, Vec2 scale, f32 rotation)
{
draw_sprite(texture, R(0, 0, 1, 1), position, scale, rotation);
}
void debug_draw_line(Vec2 to, Vec4 to_color, Vec2 from, Vec4 from_color)
{
debug_context.debug_lines[debug_context.num_debug_lines++] = to.x;
debug_context.debug_lines[debug_context.num_debug_lines++] = to.y;
debug_context.debug_lines[debug_context.num_debug_lines++] = to_color.x;
debug_context.debug_lines[debug_context.num_debug_lines++] = to_color.y;
debug_context.debug_lines[debug_context.num_debug_lines++] = to_color.z;
debug_context.debug_lines[debug_context.num_debug_lines++] = to_color.w;
debug_context.debug_lines[debug_context.num_debug_lines++] = from.x;
debug_context.debug_lines[debug_context.num_debug_lines++] = from.y;
debug_context.debug_lines[debug_context.num_debug_lines++] = from_color.x;
debug_context.debug_lines[debug_context.num_debug_lines++] = from_color.y;
debug_context.debug_lines[debug_context.num_debug_lines++] = from_color.z;
debug_context.debug_lines[debug_context.num_debug_lines++] = from_color.w;
ASSERT(debug_context.num_debug_lines < MAX_NUM_DEBUG_LINES);
}
void debug_draw_line(Vec2 to, Vec2 from, Vec4 color=V4(0.5, 0.75, 0.3, 1.0))
{
debug_context.debug_lines[debug_context.num_debug_lines++] = to.x;
debug_context.debug_lines[debug_context.num_debug_lines++] = to.y;
debug_context.debug_lines[debug_context.num_debug_lines++] = color.x;
debug_context.debug_lines[debug_context.num_debug_lines++] = color.y;
debug_context.debug_lines[debug_context.num_debug_lines++] = color.z;
debug_context.debug_lines[debug_context.num_debug_lines++] = color.w;
debug_context.debug_lines[debug_context.num_debug_lines++] = from.x;
debug_context.debug_lines[debug_context.num_debug_lines++] = from.y;
debug_context.debug_lines[debug_context.num_debug_lines++] = color.x;
debug_context.debug_lines[debug_context.num_debug_lines++] = color.y;
debug_context.debug_lines[debug_context.num_debug_lines++] = color.z;
debug_context.debug_lines[debug_context.num_debug_lines++] = color.w;
ASSERT(debug_context.num_debug_lines < MAX_NUM_DEBUG_LINES);
}
void debug_draw_point(Vec2 p, Vec4 color=V4(0.5, 0.75, 0.3, 1.0))
{
// I know this is dumb. I don't care, I love it.
debug_context.debug_points[debug_context.num_debug_points++] = p.x;
debug_context.debug_points[debug_context.num_debug_points++] = p.y;
debug_context.debug_points[debug_context.num_debug_points++] = color.x;
debug_context.debug_points[debug_context.num_debug_points++] = color.y;
debug_context.debug_points[debug_context.num_debug_points++] = color.z;
debug_context.debug_points[debug_context.num_debug_points++] = color.w;
ASSERT(debug_context.num_debug_points < MAX_NUM_DEBUG_POINTS);
}
void draw_debug(Camera *camera)
{
if (!debug_context.initalized)
{
debug_context.shader_id = load_asset(AFT_SHADER, "res/debug.glsl");
debug_context.initalized = true;
}
// Setup shader.
glLineWidth(7.5f * camera->zoom);
glPointSize(15.0f * camera->zoom);
GLuint program = find_asset(debug_context.shader_id).shader.program;
glUseProgram(program);
// Transform
glUniform2f(u_loc("position"), 0, 0);
glUniform2f(u_loc("scale"), 1, 1);
glUniform1f(u_loc("rotation"), 0);
// Camera
glUniform2f(u_loc("camera_position"), camera->position.x, camera->position.y);
glUniform1f(u_loc("camera_rotation"), camera->rotation);
glUniform1f(u_loc("camera_zoom"), camera->zoom);
glUniform1f(u_loc("aspect_ratio"), game.aspect_ratio);
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(f32) * debug_context.num_debug_lines, debug_context.debug_lines, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(f32) * (2 + 4), (void *) (0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(f32) * (2 + 4), (void *) (sizeof(f32) * 2));
glDrawArrays(GL_LINES, 0, debug_context.num_debug_lines / 6);
glDeleteBuffers(1, &vbo);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(f32) * debug_context.num_debug_points, debug_context.debug_points, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(f32) * (2 + 4), (void *) (0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(f32) * (2 + 4), (void *) (sizeof(f32) * 2));
glDrawArrays(GL_POINTS, 0, debug_context.num_debug_points / 6);
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
debug_context.num_debug_lines = 0;
debug_context.num_debug_points = 0;
}
void draw_debug()
{
draw_debug(game.camera);
}
struct Vertex
{
f32 x, y, u, v;
};
f32 messure_text(AssetID font_id, const char *_text, f32 size)
{
f32 length = 0.0;
Font font = find_asset(font_id).font;
char *text = (char *) _text;
char curr, prev = '\0'; // Only asign to prev.
while (true)
{
curr = *(text++);
if (!curr) break;
f32 kerning = find_kerning(font, prev, curr);
length += kerning;
Glyph glyph = font.glyphs[curr];
length += glyph.advance;
prev = curr;
}
return length;
}
void draw_text(AssetID font_id, const char *_text, Vec2 position, f32 size, Vec4 color,
f32 width=0.5f, f32 edge=0.15f)
{
// NOTE: You can alternatively generate a new VBO and VAO so we onlt send down one
// draw call with all the text in one. But I don't know if this is faster.
List<f32> verticies = create_list<f32>(sizeof(f32) * 4 * 6 * str_len(_text));
f32 offset = 0.0;
Font font = find_asset(font_id).font;
char *text = (char *) _text;
char curr, prev = '\0'; // Only asign to prev.
while (true)
{
curr = *(text++);
if (!curr) break;
f32 kerning = find_kerning(font, prev, curr);
const f32 spacing = 0.75f;
offset -= kerning * spacing;
Glyph glyph = font.glyphs[curr];
Rect rect = {V2(glyph.x, glyph.y), V2(glyph.w, glyph.h)};
//
// V2---V3
// | |
// | |
// V1---V4
//
// V1
verticies.append(glyph.x_offset + offset);
verticies.append(glyph.y_offset);
verticies.append(rect.min.x);
verticies.append(rect.min.y);
// V2
verticies.append(glyph.x_offset + offset);
verticies.append(glyph.y_offset + rect.dim.y);
verticies.append(rect.min.x);
verticies.append(rect.min.y + rect.dim.y);
// V3
verticies.append(glyph.x_offset + rect.dim.x + offset);
verticies.append(glyph.y_offset + rect.dim.y);
verticies.append(rect.min.x + rect.dim.x);
verticies.append(rect.min.y + rect.dim.y);
// V3
verticies.append(glyph.x_offset + rect.dim.x + offset);
verticies.append(glyph.y_offset + rect.dim.y);
verticies.append(rect.min.x + rect.dim.x);
verticies.append(rect.min.y + rect.dim.y);
// V4
verticies.append(glyph.x_offset + rect.dim.x + offset);
verticies.append(glyph.y_offset);
verticies.append(rect.min.x + rect.dim.x);
verticies.append(rect.min.y);
// V1
verticies.append(glyph.x_offset + offset);
verticies.append(glyph.y_offset);
verticies.append(rect.min.x);
verticies.append(rect.min.y);
offset += glyph.advance * spacing;
prev = curr;
}
Texture texture = find_asset(font.texture).texture;
GLuint program = find_asset(game.text_context->shader_id).shader.program;
f32 aspect = game.aspect_ratio * (texture.width / texture.height);
glUseProgram(program);
bind_texture(texture, 0);
glUniform1i(u_loc("font_atlas"), 0);
glUniform1f(u_loc("width"), width);
glUniform1f(u_loc("edge"), edge);
glUniform4f(u_loc("color"), color.x, color.y, color.z, color.w);
glUniform2f(u_loc("position"), position.x, position.y);
glUniform2f(u_loc("scale"), aspect * size, size);
glUniform1f(u_loc("rotation"), 0);
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(verticies[0]) * verticies.length, verticies.data, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(f32) * 4, (void *) (0));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(f32) * 4, (void *) (sizeof(f32) * 2));
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_TRIANGLES, 0, verticies.length / 4);
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
destroy_list(&verticies);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#include "core/pch.h"
#ifdef M2_SUPPORT
#include "adjunct/m2_ui/dialogs/OfflineMessagesDialog.h"
#include "adjunct/m2/src/engine/engine.h"
#include "modules/locale/locale-enum.h"
#include "modules/locale/oplanguagemanager.h"
/***********************************************************************************
** Initialization
**
** OfflineMessagesDialog::Init
** @param parent_window
** @param account_id
***********************************************************************************/
OP_STATUS OfflineMessagesDialog::Init(DesktopWindow* parent_window,
UINT16 account_id)
{
// Save account_id for use in OnOk()
m_account_id = account_id;
// Construct dialog
OpString title, message;
RETURN_IF_ERROR(g_languageManager->GetString(Str::D_MAIL_MAKE_OFFLINE_MESSAGES_AVAILABLE_TITLE, title));
RETURN_IF_ERROR(g_languageManager->GetString(Str::D_MAIL_MAKE_OFFLINE_MESSAGES_AVAILABLE, message));
return SimpleDialog::Init(WINDOW_NAME_OFFLINE_MESSAGES, title, message, parent_window, Dialog::TYPE_YES_NO, Dialog::IMAGE_QUESTION);
}
/***********************************************************************************
**
**
** OfflineMessagesDialog::OnOk
***********************************************************************************/
UINT32 OfflineMessagesDialog::OnOk()
{
g_m2_engine->EnsureAllBodiesDownloaded(IndexTypes::FIRST_ACCOUNT + m_account_id);
return SimpleDialog::OnOk();
}
#endif // M2_SUPPORT
|
/*
* Main.cpp
*
* Created on: 2021. 6. 9.
* Author: dhjeong
*/
#include "test/source.cpp"
#include <vector>
#include <string>
int main(void) {
test test;
test.run();
std::vector<std::string> strList;
strList.push_back("test");
for (int i=0; i<strList.size(); i++) {
}
}
|
#include <iostream>
typedef long long ll;
using namespace std;
ll n, q, k, a[100000], first, second, firstEnd, secondEnd, temp;
bool alwaysK;
string Q;
void findLongestTwo()
{
ll end = n, j, current;
first = second = current = 0;
if (a[n - 1] == 1 && a[0] == 1)
for (j = n - 1; j >= 0; j--)
{
if (a[j] == 1)
{
end--;
current++;
}
else
break;
}
for (j = 0; j < end; j++)
{
if (a[j] == 0)
{
if (current > first)
{
second = first;
first = current;
secondEnd = firstEnd;
firstEnd = j - 1;
// cout << "first and second change to " << first << " " << second << endl;
}
else if (current > second)
{
second = current;
secondEnd = j - 1;
}
current = 0;
}
else
{
current++;
// cout << current << " c" << endl;
}
}
if (current > first)
{
second = first;
secondEnd = firstEnd;
first = current;
firstEnd = end - 1;
}
else if (current > second)
{
second = current;
secondEnd = end - 1;
}
//check if all are 1
if (firstEnd == -1)
{
firstEnd = n - 1;
alwaysK = true;
//little hack
if(n < k)
k = n;
}
// cout << "first and second are " << first << " " << second << endl;
// cout << "first end and second end" << firstEnd << " " << secondEnd << endl;
if ((first >= 2 * k) || (first >= k && second >= k))
alwaysK = true;
// cout << "always k " << alwaysK << endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> q >> k;
for (int i = 0; i < n; i++)
cin >> a[i];
cin >> Q;
alwaysK = false;
findLongestTwo();
// if(first > k)
// first = k;
// if(second > k)
// second = k;
if (alwaysK)
{
for (int i = 0; i < q; i++)
if (Q[i] == '?')
cout << k << endl;
}
else
for (int i = 0; i < q; i++)
{
if (Q[i] == '!')
{
firstEnd = (firstEnd + 1) % n;
secondEnd = (secondEnd + 1) % n;
continue;
}
if (firstEnd >= k - 1)
{
if (first >= k)
cout << k << endl;
else
cout << first << endl;
}
else
{
temp = max(firstEnd + 1, abs(first - firstEnd - 1));
temp = min(temp, first);
// cout << firstEnd + 1 << " in " << abs(first - firstEnd - 1) << endl;
if (temp > second)
{
if (temp >= k)
cout << k << endl;
else
cout << temp << endl;
}
else
cout << second << endl;
}
}
}
|
#ifndef WORLD_H
#define WORLD_H
#include "nbt.h"
#include "chunk.h"
#include "types.h"
#include <unordered_map>
class World {
protected:
std::unordered_map<int32, std::unordered_map<int32, Chunk> > chunks;
public:
World(std::string file);
World();
World(nbttag w);
};
#endif
|
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <iterator>
#include <algorithm>
std::vector<std::string> split(std::string toSplit, const char delimiter)
{
std::stringstream ss(toSplit);
std::string token;
std::vector<std::string> splitString;
while (std::getline(ss, token, delimiter))
{
splitString.emplace_back(token);
}
return splitString;
}
std::vector<std::string> splitFirst(std::string Line, const char delimiter)
{
bool found{false};
std::vector<std::string> splitString;
std::string key;
std::string value;
for (char symbol : Line)
{
if (symbol == delimiter && !found)
{
found = true;
}
else if (symbol != delimiter && !found)
{
key += symbol;
}
else if (symbol != delimiter && found)
{
value += symbol;
}
}
splitString.emplace_back(key);
splitString.emplace_back(value);
return splitString;
}
bool valIsInt(std::string value)
{
return false;
}
bool valIsFloat(std::string value)
{
return false;
}
template <typename K, typename V>
struct keyPair
{
K key;
V value;
};
struct List
{
std::vector<std::string> elements;
};
template <typename K, typename V>
struct Dictionary
{
std::vector<keyPair<K, V>> elements;
};
class duoParser
{
private:
std::ifstream file;
int curObjectID{0};
std::string curObjectName;
keyPair<std::string, std::string> curPair{"", " "};
public:
duoParser(std::string path)
{
file = std::ifstream(path);
if (!file)
{
std::cerr << path << " could not be opened\n";
exit(1);
}
}
~duoParser()
{
file.close();
}
bool isNewDoc(std::string line)
{
if (line == "---")
{
std::cout << "new document\n";
curObjectID++;
return true;
}
return false;
}
bool containsInfo(std::string line)
{
if (line != "")
return true;
return false;
}
void printPair(std::string line)
{
std::vector<std::string> tempVect = splitFirst(line, ':');
curPair.key = tempVect[0];
curPair.value = tempVect[1];
std::cout << curPair.key << ", " << curPair.value << std::endl;
}
void parse()
{
std::string curLine;
while (std::getline(file, curLine))
{
if (!containsInfo(curLine))
continue;
if (isNewDoc(curLine))
continue;
printPair(curLine);
}
}
};
int main(int argc, char const *argv[])
{
duoParser parser("test.yaml");
parser.parse();
float test(0.0f);
return 0;
}
|
/*!
* \file transition.h
* \author Simon Coakley
* \date 2012
* \copyright Copyright (c) 2012 University of Sheffield
* \brief Header file for transition function
*/
#ifndef TRANSITION_H_
#define TRANSITION_H_
#include "./mpre.h"
#include "./mpost.h"
#include "./state.h"
#include "./memorymodel.h"
#include "./condition.h"
#include "./communication.h"
class Transition {
public:
Transition();
Transition(State * cs, QString n, State * ns);
Transition(State * cs, Communication i, Mpre pre,
QString n, Mpost post, Communication o, State * ns);
void setCurrentState(State * cs) { myCurrentState = cs; }
State * currentState() const { return myCurrentState; }
void setInput(Communication i) { myInput = i; }
Communication input() const { return myInput; }
void setMpre(Mpre pre) { myMpre = pre; }
Mpre mpre() const { return myMpre; }
void setName(QString n) { myName = n; }
QString name() const { return myName; }
void setMpost(Mpost post) { myMpost = post; }
Mpost mpost() const { return myMpost; }
void setOutput(Communication o) { myOutput = o; }
Communication output() const { return myOutput; }
void setNextState(State * ns) { myNextState = ns; }
State * nextState() const { return myNextState; }
Mpre * getMprePointer() { return &myMpre; }
void setCondition(Condition c) { myCondition = c; }
Condition condition() const { return myCondition; }
void setDescription(QString s) { myDescription = s; }
QString description() const { return myDescription; }
bool passesCondition(MemoryModel * memory);
void updateMemory(MemoryModel * memory);
private:
State * myCurrentState;
Communication myInput;
Mpre myMpre;
QString myName;
Mpost myMpost;
Communication myOutput;
State * myNextState;
Condition myCondition;
QString myDescription;
};
#endif // TRANSITION_H_
|
#include "ip_filter.h"
#include <gtest/gtest.h>
#include <vector>
#include <random>
#include <limits>
TEST(split_string, without_TAB) {
// Arrange
std::string str{""};
// Act
std::vector<std::string> keeper = split(str);
// Assert
ASSERT_EQ(keeper.size(), 1);
}
TEST(split_string, one_TAB) {
// Arrange
std::string str{"1\t2"};
// Act
std::vector<std::string> keeper = split(str);
// Assert
ASSERT_EQ(keeper.size(), 2);
}
TEST(split_string, two_TAB) {
// Arrange
std::string str{"1\t2\tnexttxt"};
// Act
std::vector<std::string> keeper = split(str);
// Assert
ASSERT_EQ(keeper.size(), 3);
}
TEST(split_string, more_than_two_TAB) {
// Arrange
std::string str{"1\t2\tn\ne\tx\tt\nt\vx\tt"};
// Act
std::vector<std::string> keeper = split(str);
// Assert
ASSERT_EQ(keeper.size(), 6);
}
TEST(split_ip, test_valid_IPv4) {
// Arrange
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<unsigned int> dis_ui(0, 255);
auto rand_string_IPv4 = [&dis_ui, &gen]()
{
return std::to_string(dis_ui(gen)) + "." + std::to_string(dis_ui(gen)) + "."
+ std::to_string(dis_ui(gen)) + "." + std::to_string(dis_ui(gen));
};
// Act
std::vector<std::vector<uint32_t>> keeper(10000);
for(unsigned i{0}; i < 10000; ++i)
keeper.at(i) = split_ip(rand_string_IPv4());
// Assert
ASSERT_EQ(keeper.size(), 10000);
}
TEST(regexprTABS, in_string_exactly_two_TABs) {
// Arrange
ipv4_validate validatorTwoTabs(".*\\t.*\\t.*");
std::vector<std::string> keeper{"", "jkgjfjaiewi", "a\tb", "a\tbcbn\tcvmnc", "a\tb\t", "\tb\tjfdgfdklg\t \t", "1\t2\tn\ne\tx\tt\nt\vx\tt"};
std::vector<std::string> valid_str;
// Act
for(unsigned i{0}; i < 7; ++i)
{
if(validatorTwoTabs(keeper.at(i)))
valid_str.push_back(keeper.at(i));
}
// Assert
ASSERT_EQ(valid_str.size(), 3);
}
TEST(regexprIP, test_valid_IPv4) {
// Arrange
ipv4_validate validatorIP;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<unsigned int> dis_ui(0, 255);
auto rand_string_IPv4 = [&dis_ui, &gen]()
{
return std::to_string(dis_ui(gen)) + "." + std::to_string(dis_ui(gen)) + "."
+ std::to_string(dis_ui(gen)) + "." + std::to_string(dis_ui(gen));
};
// Act
std::vector<std::string> keeper;
for(unsigned i{0}; i < 10000; ++i)
{
std::string str = rand_string_IPv4();
if(validatorIP(str))
keeper.push_back(str);
}
// Assert
ASSERT_EQ(keeper.size(), 10000);
}
TEST(regexprIP, first_invalid_IPv4) {
// Arrange
ipv4_validate validatorIP;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<unsigned int> dis_ui(256, std::numeric_limits<unsigned int>::max());
auto rand_string_IPv4 = [&dis_ui, &gen]()
{
return std::to_string(dis_ui(gen)) + "." + std::to_string(dis_ui(gen)) + "."
+ std::to_string(dis_ui(gen)) + "." + std::to_string(dis_ui(gen));
};
// Act
std::vector<std::string> keeper;
for(unsigned i{0}; i < 10000; ++i)
{
std::string str = rand_string_IPv4();
if(validatorIP(str))
keeper.push_back(str);
}
// Assert
ASSERT_EQ(keeper.size(), 0);
}
TEST(regexprIP, second_invalid_IPv4) {
// Arrange
ipv4_validate validatorIP;
std::vector<std::string> keeper{"", "0", "1.1", ".11", "11.",
".22.2", "2.2.2",
"3.3.3.", ".3.3.3", ".3.33.", "...",
"4.4.4.4.4", ".44.4.444.",
"5.5.5.5.5.5"};
std::vector<std::string> valid_str;
// Act
for(unsigned i{0}; i < 14; ++i)
if(validatorIP(keeper.at(i)))
valid_str.push_back(keeper.at(i));
// Assert
ASSERT_EQ(valid_str.size(), 0);
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Christopher Blizzard.
* Portions created by Christopher Blizzard are Copyright (C)
* Christopher Blizzard. All Rights Reserved.
*
* Contributor(s):
* Christopher Blizzard <blizzard@mozilla.org>
*/
#include <nsIDocShell.h>
#include <nsIWebProgress.h>
#include <nsIWebBrowserFocus.h>
#include <nsCRT.h>
#if 0
#include <nsNetUtil.h>
#include <nsIWebBrowserStream.h>
#endif
// for NS_APPSHELL_CID
#include <nsWidgetsCID.h>
// for do_GetInterface
#include <nsIInterfaceRequestor.h>
// for do_CreateInstance
#include <nsIComponentManager.h>
// for initializing our window watcher service
#include <nsIWindowWatcher.h>
//#include <nsILocalFile.h>
#include <nsEmbedAPI.h>
// all of the crap that we need for event listeners
// and when chrome windows finish loading
#include <nsIDOMWindow.h>
#include <nsIDOMWindowInternal.h>
// For seting scrollbar visibilty
#include <nsIDOMBarProp.h>
// app component registration
#include <nsIGenericFactory.h>
#include <nsIComponentRegistrar.h>
#include <nsISupportsUtils.h>
// all of our local includes
#include "EmbedPrivate.h"
#include "EmbedWindow.h"
#include "EmbedProgress.h"
#include "EmbedContentListener.h"
#include "EmbedEventListener.h"
#include "EmbedWindowCreator.h"
#include "EmbedStream.h"
#include "GtkPromptService.h"
#include "MozillaPrivate.h"
#ifdef MOZ_ACCESSIBILITY_ATK
#include "nsIAccessibilityService.h"
#include "nsIAccessible.h"
#include "nsIDOMDocument.h"
#endif
#ifdef _BUILD_STATIC_BIN
#include "nsStaticComponent.h"
nsresult PR_CALLBACK
gtk_getModuleInfo(nsStaticModuleInfo **info, PRUint32 *count);
#endif
static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID);
PRUint32 EmbedPrivate::sWidgetCount = 0;
char *EmbedPrivate::sCompPath = nsnull;
nsIAppShell *EmbedPrivate::sAppShell = nsnull;
GList *EmbedPrivate::sWindowList = NULL;
char *EmbedPrivate::sProfileDir = nsnull;
char *EmbedPrivate::sProfileName = nsnull;
GtkWidget *EmbedPrivate::sOffscreenWindow = 0;
GtkWidget *EmbedPrivate::sOffscreenFixed = 0;
nsIDirectoryServiceProvider *EmbedPrivate::sAppFileLocProvider = nsnull;
MozillaEmbedPrivate *EmbedPrivate::sMozillaEmbedPrivate = nsnull;
#if 0
#define NS_PROMPTSERVICE_CID \
{0x95611356, 0xf583, 0x46f5, {0x81, 0xff, 0x4b, 0x3e, 0x01, 0x62, 0xc6, 0x19}}
NS_GENERIC_FACTORY_CONSTRUCTOR(GtkPromptService)
static const nsModuleComponentInfo defaultAppComps[] = {
{
"Prompt Service",
NS_PROMPTSERVICE_CID,
"@mozilla.org/embedcomp/prompt-service;1",
GtkPromptServiceConstructor
}
};
const nsModuleComponentInfo *EmbedPrivate::sAppComps = defaultAppComps;
int EmbedPrivate::sNumAppComps = sizeof(defaultAppComps) / sizeof(nsModuleComponentInfo);
#endif
EmbedPrivate::EmbedPrivate(void)
{
mOwningWidget = nsnull;
mWindow = nsnull;
mProgress = nsnull;
mContentListener = nsnull;
mEventListener = nsnull;
mStream = nsnull;
mChromeMask = nsIWebBrowserChrome::CHROME_ALL;
mIsChrome = PR_FALSE;
mChromeLoaded = PR_FALSE;
mListenersAttached = PR_FALSE;
mMozWindowWidget = 0;
mIsDestroyed = PR_FALSE;
PushStartup();
sWindowList = g_list_append(sWindowList, this);
}
EmbedPrivate::~EmbedPrivate()
{
sWindowList = g_list_remove(sWindowList, this);
PopStartup();
}
nsresult
EmbedPrivate::Init(GtkMozEmbed *aOwningWidget)
{
// are we being re-initialized?
if (mOwningWidget)
return NS_OK;
// hang on with a reference to the owning widget
mOwningWidget = aOwningWidget;
// Create our embed window, and create an owning reference to it and
// initialize it. It is assumed that this window will be destroyed
// when we go out of scope.
mWindow = new EmbedWindow();
mWindowGuard = NS_STATIC_CAST(nsIWebBrowserChrome *, mWindow);
mWindow->Init(this);
// Create our progress listener object, make an owning reference,
// and initialize it. It is assumed that this progress listener
// will be destroyed when we go out of scope.
mProgress = new EmbedProgress();
mProgressGuard = NS_STATIC_CAST(nsIWebProgressListener *,
mProgress);
mProgress->Init(this);
// Create our content listener object, initialize it and attach it.
// It is assumed that this will be destroyed when we go out of
// scope.
mContentListener = new EmbedContentListener();
mContentListenerGuard = NS_STATIC_CAST(nsISupports*, NS_STATIC_CAST(nsIURIContentListener*, mContentListener));
mContentListener->Init(this);
// Create our key listener object and initialize it. It is assumed
// that this will be destroyed before we go out of scope.
mEventListener = new EmbedEventListener();
mEventListenerGuard =
NS_STATIC_CAST(nsISupports *, NS_STATIC_CAST(nsIDOMKeyListener *,
mEventListener));
mEventListener->Init(this);
// has the window creator service been set up?
static int initialized = PR_FALSE;
// Set up our window creator ( only once )
if (!initialized) {
// We set this flag here instead of on success. If it failed we
// don't want to keep trying and leaking window creator objects.
initialized = PR_TRUE;
// create our local object
EmbedWindowCreator *creator = new EmbedWindowCreator();
nsCOMPtr<nsIWindowCreator> windowCreator;
windowCreator = NS_STATIC_CAST(nsIWindowCreator *, creator);
// Attach it via the watcher service
nsCOMPtr<nsIWindowWatcher> watcher = do_GetService(NS_WINDOWWATCHER_CONTRACTID);
if (watcher)
watcher->SetWindowCreator(windowCreator);
}
return NS_OK;
}
nsresult
EmbedPrivate::Realize(PRBool *aAlreadyRealized)
{
*aAlreadyRealized = PR_FALSE;
// create the offscreen window if we have to
EnsureOffscreenWindow();
// Have we ever been initialized before? If so then just reparetn
// from the offscreen window.
if (mMozWindowWidget) {
gtk_widget_reparent(mMozWindowWidget, GTK_WIDGET(mOwningWidget));
*aAlreadyRealized = PR_TRUE;
return NS_OK;
}
// Get the nsIWebBrowser object for our embedded window.
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
// get a handle on the navigation object
mNavigation = do_QueryInterface(webBrowser);
// Create our session history object and tell the navigation object
// to use it. We need to do this before we create the web browser
// window.
mSessionHistory = do_CreateInstance(NS_SHISTORY_CONTRACTID);
mNavigation->SetSessionHistory(mSessionHistory);
// create the window
mWindow->CreateWindow();
// bind the progress listener to the browser object
nsCOMPtr<nsISupportsWeakReference> supportsWeak;
supportsWeak = do_QueryInterface(mProgressGuard);
nsCOMPtr<nsIWeakReference> weakRef;
supportsWeak->GetWeakReference(getter_AddRefs(weakRef));
webBrowser->AddWebBrowserListener(weakRef,
nsIWebProgressListener::GetIID());
// set ourselves as the parent uri content listener
nsCOMPtr<nsIURIContentListener> uriListener;
uriListener = do_QueryInterface(mContentListenerGuard);
webBrowser->SetParentURIContentListener(uriListener);
// save the window id of the newly created window
// get the native drawing area
GdkWindow *tmp_window = MozillaPrivate::GetGdkWindow(mWindow->mBaseWindow);
// and, thanks to superwin we actually need the parent of that.
tmp_window = gdk_window_get_parent(tmp_window);
// save the widget ID - it should be the mozarea of the window.
gpointer data = nsnull;
gdk_window_get_user_data(tmp_window, &data);
mMozWindowWidget = NS_STATIC_CAST(GtkWidget *, data);
// Apply the current chrome mask
ApplyChromeMask();
return NS_OK;
}
void
EmbedPrivate::Unrealize(void)
{
// reparent to our offscreen window
gtk_widget_reparent(mMozWindowWidget, sOffscreenFixed);
}
void
EmbedPrivate::Show(void)
{
// Get the nsIWebBrowser object for our embedded window.
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
// and set the visibility on the thing
nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(webBrowser);
baseWindow->SetVisibility(PR_TRUE);
}
void
EmbedPrivate::Hide(void)
{
// Get the nsIWebBrowser object for our embedded window.
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
// and set the visibility on the thing
nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(webBrowser);
baseWindow->SetVisibility(PR_FALSE);
}
void
EmbedPrivate::Resize(PRUint32 aWidth, PRUint32 aHeight)
{
mWindow->SetDimensions(nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION |
nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_INNER,
0, 0, aWidth, aHeight);
}
void
EmbedPrivate::GetSize(PRInt32 *aWidth, PRInt32 *aHeight)
{
mWindow->GetDimensions(nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_INNER,
nsnull, nsnull, aWidth, aHeight);
}
void
EmbedPrivate::Destroy(void)
{
// This flag might have been set from
// EmbedWindow::DestroyBrowserWindow() as well if someone used a
// window.close() or something or some other script action to close
// the window. No harm setting it again.
mIsDestroyed = PR_TRUE;
// Get the nsIWebBrowser object for our embedded window.
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
// Release our progress listener
nsCOMPtr<nsISupportsWeakReference> supportsWeak;
supportsWeak = do_QueryInterface(mProgressGuard);
nsCOMPtr<nsIWeakReference> weakRef;
supportsWeak->GetWeakReference(getter_AddRefs(weakRef));
webBrowser->RemoveWebBrowserListener(weakRef,
nsIWebProgressListener::GetIID());
weakRef = nsnull;
supportsWeak = nsnull;
// Release our content listener
webBrowser->SetParentURIContentListener(nsnull);
mContentListenerGuard = nsnull;
mContentListener = nsnull;
// Now that we have removed the listener, release our progress
// object
mProgressGuard = nsnull;
mProgress = nsnull;
// detach our event listeners and release the event receiver
DetachListeners();
if (mEventReceiver)
mEventReceiver = nsnull;
// destroy our child window
mWindow->ReleaseChildren();
// release navigation
mNavigation = nsnull;
// release session history
mSessionHistory = nsnull;
mOwningWidget = nsnull;
mMozWindowWidget = 0;
}
void
EmbedPrivate::SetURI(const char *aURI)
{
NS_CStringToUTF16(nsEmbedCString(aURI),
NS_CSTRING_ENCODING_UTF8, mURI);
}
void
EmbedPrivate::LoadCurrentURI(void)
{
if (mURI.Length()) {
#if 0
nsCOMPtr<nsPIDOMWindow> piWin;
GetPIDOMWindow(getter_AddRefs(piWin));
nsAutoPopupStatePusher popupStatePusher(piWin, openAllowed);
#endif
mNavigation->LoadURI(mURI.get(), // URI string
nsIWebNavigation::LOAD_FLAGS_NONE, // Load flags
nsnull, // Referring URI
nsnull, // Post data
nsnull); // extra headers
}
}
void
EmbedPrivate::Reload(PRUint32 reloadFlags)
{
/* Use the session history if it is available, this
* allows framesets to reload correctly */
nsCOMPtr<nsIWebNavigation> wn;
if (mSessionHistory) {
wn = do_QueryInterface(mSessionHistory);
}
if (!wn)
wn = mNavigation;
if (wn)
wn->Reload(reloadFlags);
}
void
EmbedPrivate::ApplyChromeMask()
{
if (mWindow) {
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
nsCOMPtr<nsIDOMWindow> domWindow;
webBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));
if (domWindow) {
nsCOMPtr<nsIDOMBarProp> scrollbars;
domWindow->GetScrollbars(getter_AddRefs(scrollbars));
if (scrollbars) {
scrollbars->SetVisible
(mChromeMask & nsIWebBrowserChrome::CHROME_SCROLLBARS ?
PR_TRUE : PR_FALSE);
}
}
}
}
void
EmbedPrivate::SetChromeMask(PRUint32 aChromeMask)
{
mChromeMask = aChromeMask;
ApplyChromeMask();
}
/* static */
void
EmbedPrivate::PushStartup(void)
{
// increment the number of widgets
sWidgetCount++;
// if this is the first widget, fire up xpcom
if (sWidgetCount == 1) {
nsresult rv;
nsCOMPtr<nsILocalFile> binDir;
if (sCompPath) {
rv = NS_NewNativeLocalFile(nsEmbedCString(sCompPath), 1, getter_AddRefs(binDir));
if (NS_FAILED(rv))
return;
}
#ifdef _BUILD_STATIC_BIN
// Initialize XPCOM's module info table
NSGetStaticModuleInfo = gtk_getModuleInfo;
#endif
rv = NS_InitEmbedding(binDir, sAppFileLocProvider);
if (NS_FAILED(rv))
return;
// we no longer need a reference to the DirectoryServiceProvider
if (sAppFileLocProvider) {
NS_RELEASE(sAppFileLocProvider);
sAppFileLocProvider = nsnull;
}
sMozillaEmbedPrivate = new MozillaEmbedPrivate;
rv = sMozillaEmbedPrivate->StartupProfile(sProfileDir, sProfileName);
NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Warning: Failed to start up profiles.\n");
rv = RegisterAppComponents();
NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Warning: Failed to register app components.\n");
// XXX startup appshell service?
// XXX create offscreen window for appshell service?
// XXX remove X prop from offscreen window?
nsCOMPtr<nsIAppShell> appShell;
appShell = do_CreateInstance(kAppShellCID);
if (!appShell) {
NS_WARNING("Failed to create appshell in EmbedPrivate::PushStartup!\n");
return;
}
sAppShell = appShell.get();
NS_ADDREF(sAppShell);
sAppShell->Create(0, nsnull);
sAppShell->Spinup();
}
}
/* static */
void
EmbedPrivate::PopStartup(void)
{
sWidgetCount--;
if (sWidgetCount == 0) {
// destroy the offscreen window
DestroyOffscreenWindow();
// shut down the profiles
sMozillaEmbedPrivate->ShutdownProfile();
if (sAppShell) {
// Shutdown the appshell service.
sAppShell->Spindown();
NS_RELEASE(sAppShell);
sAppShell = 0;
}
delete sMozillaEmbedPrivate;
// shut down XPCOM/Embedding
NS_TermEmbedding();
}
}
/* static */
void
EmbedPrivate::SetCompPath(const char *aPath)
{
if (sCompPath)
free(sCompPath);
if (aPath)
sCompPath = strdup(aPath);
else
sCompPath = nsnull;
}
/* static */
void
EmbedPrivate::SetAppComponents(const nsModuleComponentInfo* aComps,
int aNumComponents)
{
// sAppComps = aComps;
// sNumAppComps = aNumComponents;
}
/* static */
void
EmbedPrivate::SetProfilePath(const char *aDir, const char *aName)
{
if (sProfileDir) {
nsMemory::Free(sProfileDir);
sProfileDir = nsnull;
}
if (sProfileName) {
nsMemory::Free(sProfileName);
sProfileName = nsnull;
}
if (aDir)
sProfileDir = (char *)nsMemory::Clone(aDir, strlen(aDir) + 1);
if (aName)
sProfileName = (char *)nsMemory::Clone(aName, strlen(aName) + 1);
}
void
EmbedPrivate::SetDirectoryServiceProvider(nsIDirectoryServiceProvider * appFileLocProvider)
{
if (sAppFileLocProvider)
NS_RELEASE(sAppFileLocProvider);
if (appFileLocProvider) {
sAppFileLocProvider = appFileLocProvider;
NS_ADDREF(sAppFileLocProvider);
}
}
#if 1
nsresult
EmbedPrivate::OpenStream(const char *aBaseURI, const char *aContentType)
{
nsresult rv;
if (!mStream) {
mStream = new EmbedStream();
mStreamGuard = do_QueryInterface(mStream);
mStream->InitOwner(this);
rv = mStream->Init();
if (NS_FAILED(rv))
return rv;
}
rv = mStream->OpenStream(aBaseURI, aContentType);
}
nsresult
EmbedPrivate::AppendToStream(const char *aData, PRInt32 aLen)
{
if (!mStream)
return NS_ERROR_FAILURE;
// Attach listeners to this document since in some cases we don't
// get updates for content added this way.
ContentStateChange();
return mStream->AppendToStream(aData, aLen);
}
nsresult
EmbedPrivate::CloseStream(void)
{
nsresult rv;
if (!mStream)
return NS_ERROR_FAILURE;
rv = mStream->CloseStream();
// release
mStream = 0;
mStreamGuard = 0;
return rv;
}
#endif
#if 0
nsresult
EmbedPrivate::OpenStream(const char *aBaseURI, const char *aContentType)
{
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
nsCOMPtr<nsIWebBrowserStream> wbStream = do_QueryInterface(webBrowser);
if (!wbStream) return NS_ERROR_FAILURE;
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_NewURI(getter_AddRefs(uri), aBaseURI);
if (NS_FAILED(rv))
return rv;
rv = wbStream->OpenStream(uri, nsDependentCString(aContentType));
return rv;
}
nsresult
EmbedPrivate::AppendToStream(const PRUint8 *aData, PRUint32 aLen)
{
// Attach listeners to this document since in some cases we don't
// get updates for content added this way.
ContentStateChange();
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
nsCOMPtr<nsIWebBrowserStream> wbStream = do_QueryInterface(webBrowser);
if (!wbStream) return NS_ERROR_FAILURE;
return wbStream->AppendToStream(aData, aLen);
}
nsresult
EmbedPrivate::CloseStream(void)
{
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
nsCOMPtr<nsIWebBrowserStream> wbStream = do_QueryInterface(webBrowser);
if (!wbStream) return NS_ERROR_FAILURE;
return wbStream->CloseStream();
}
#endif
/* static */
EmbedPrivate *
EmbedPrivate::FindPrivateForBrowser(nsIWebBrowserChrome *aBrowser)
{
if (!sWindowList)
return nsnull;
// Get the number of browser windows.
PRInt32 count = (PRInt32)g_list_length(sWindowList);
// This function doesn't get called very often at all ( only when
// creating a new window ) so it's OK to walk the list of open
// windows.
for (int i = 0; i < count; i++) {
EmbedPrivate *tmpPrivate = NS_STATIC_CAST(EmbedPrivate *,
g_list_nth_data(sWindowList, i));
// get the browser object for that window
nsIWebBrowserChrome *chrome = NS_STATIC_CAST(nsIWebBrowserChrome *,
tmpPrivate->mWindow);
if (chrome == aBrowser)
return tmpPrivate;
}
return nsnull;
}
void
EmbedPrivate::ContentStateChange(void)
{
// we don't attach listeners to chrome
if (mListenersAttached && !mIsChrome)
return;
GetListener();
if (!mEventReceiver)
return;
AttachListeners();
}
void
EmbedPrivate::ContentFinishedLoading(void)
{
if (mIsChrome) {
// We're done loading.
mChromeLoaded = PR_TRUE;
// get the web browser
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
// get the content DOM window for that web browser
nsCOMPtr<nsIDOMWindow> domWindow;
webBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));
if (!domWindow) {
NS_WARNING("no dom window in content finished loading\n");
return;
}
// resize the content
domWindow->SizeToContent();
// and since we're done loading show the window, assuming that the
// visibility flag has been set.
PRBool visibility;
mWindow->GetVisibility(&visibility);
if (visibility)
mWindow->SetVisibility(PR_TRUE);
}
}
// handle focus in and focus out events
void
EmbedPrivate::ChildFocusIn(void)
{
nsresult result;
if (mIsDestroyed)
return;
nsCOMPtr<nsIWebBrowser> webBrowser;
result = mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
if (NS_FAILED (result)) return;
nsCOMPtr<nsIWebBrowserFocus> webBrowserFocus;
webBrowserFocus = do_QueryInterface (webBrowser);
if (!webBrowserFocus) return;
webBrowserFocus->Activate();
}
void
EmbedPrivate::ChildFocusOut(void)
{
nsresult result;
if (mIsDestroyed)
return;
nsCOMPtr<nsIWebBrowser> webBrowser;
result = mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
if (NS_FAILED (result)) return;
nsCOMPtr<nsIWebBrowserFocus> webBrowserFocus;
webBrowserFocus = do_QueryInterface (webBrowser);
if (!webBrowserFocus) return;
webBrowserFocus->Deactivate();
}
// Get the event listener for the chrome event handler.
void
EmbedPrivate::GetListener(void)
{
if (mEventReceiver)
return;
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
// get the content DOM window for that web browser
nsCOMPtr<nsIDOMWindow> domWindow;
webBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));
if (!domWindow)
return;
MozillaPrivate::GetEventReceiver(domWindow, getter_AddRefs(mEventReceiver));
}
// attach key and mouse event listeners
void
EmbedPrivate::AttachListeners(void)
{
if (!mEventReceiver || mListenersAttached)
return;
nsIDOMEventListener *eventListener =
NS_STATIC_CAST(nsIDOMEventListener *,
NS_STATIC_CAST(nsIDOMKeyListener *, mEventListener));
// add the key listener
nsresult rv;
rv = mEventReceiver->AddEventListenerByIID(eventListener,
NS_GET_IID(nsIDOMKeyListener));
if (NS_FAILED(rv)) {
NS_WARNING("Failed to add key listener\n");
return;
}
rv = mEventReceiver->AddEventListenerByIID(eventListener,
NS_GET_IID(nsIDOMMouseListener));
if (NS_FAILED(rv)) {
NS_WARNING("Failed to add mouse listener\n");
return;
}
rv = mEventReceiver->AddEventListenerByIID(eventListener,
NS_GET_IID(nsIDOMEventListener));
#if 0
const PRUnichar domLiteral[] = { 'D', 'O', 'M', 'L', 'i', 'n', 'k',
'A', 'd', 'd', 'e', 'd', '\0' };
nsCOMPtr<nsIDOMEventTarget> target;
target = do_QueryInterface (mEventReceiver);
target->AddEventListener(nsEmbedString(domLiteral),
eventListener, PR_FALSE);
#endif
#if 0
rv = mEventReceiver->AddEventListenerByIID(eventListener,
NS_GET_IID(nsIDOMUIListener));
if (NS_FAILED(rv)) {
NS_WARNING("Failed to add UI listener\n");
return;
}
#endif
// ok, all set.
mListenersAttached = PR_TRUE;
}
void
EmbedPrivate::DetachListeners(void)
{
if (!mListenersAttached || !mEventReceiver)
return;
nsIDOMEventListener *eventListener =
NS_STATIC_CAST(nsIDOMEventListener *,
NS_STATIC_CAST(nsIDOMKeyListener *, mEventListener));
nsresult rv;
rv = mEventReceiver->RemoveEventListenerByIID(eventListener,
NS_GET_IID(nsIDOMKeyListener));
if (NS_FAILED(rv)) {
NS_WARNING("Failed to remove key listener\n");
return;
}
rv =
mEventReceiver->RemoveEventListenerByIID(eventListener,
NS_GET_IID(nsIDOMMouseListener));
if (NS_FAILED(rv)) {
NS_WARNING("Failed to remove mouse listener\n");
return;
}
#if 0
rv = mEventReceiver->RemoveEventListenerByIID(eventListener,
NS_GET_IID(nsIDOMUIListener));
if (NS_FAILED(rv)) {
NS_WARNING("Failed to remove UI listener\n");
return;
}
#endif
mListenersAttached = PR_FALSE;
}
#if 0
nsresult
EmbedPrivate::GetPIDOMWindow(nsPIDOMWindow **aPIWin)
{
*aPIWin = nsnull;
// get the web browser
nsCOMPtr<nsIWebBrowser> webBrowser;
mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
// get the content DOM window for that web browser
nsCOMPtr<nsIDOMWindow> domWindow;
webBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));
if (!domWindow)
return NS_ERROR_FAILURE;
// get the private DOM window
nsCOMPtr<nsPIDOMWindow> domWindowPrivate = do_QueryInterface(domWindow);
// and the root window for that DOM window
nsCOMPtr<nsIDOMWindowInternal> rootWindow;
domWindowPrivate->GetPrivateRoot(getter_AddRefs(rootWindow));
nsCOMPtr<nsIChromeEventHandler> chromeHandler;
nsCOMPtr<nsPIDOMWindow> piWin(do_QueryInterface(rootWindow));
*aPIWin = piWin.get();
if (*aPIWin) {
NS_ADDREF(*aPIWin);
return NS_OK;
}
return NS_ERROR_FAILURE;
}
#endif
#ifdef MOZ_ACCESSIBILITY_ATK
void *
EmbedPrivate::GetAtkObjectForCurrentDocument()
{
if (!mNavigation)
return nsnull;
nsCOMPtr<nsIAccessibilityService> accService =
do_GetService("@mozilla.org/accessibilityService;1");
if (accService) {
//get current document
nsCOMPtr<nsIDOMDocument> domDoc;
mNavigation->GetDocument(getter_AddRefs(domDoc));
NS_ENSURE_TRUE(domDoc, nsnull);
nsCOMPtr<nsIDOMNode> domNode(do_QueryInterface(domDoc));
NS_ENSURE_TRUE(domNode, nsnull);
nsCOMPtr<nsIAccessible> acc;
accService->GetAccessibleFor(domNode, getter_AddRefs(acc));
NS_ENSURE_TRUE(acc, nsnull);
void *atkObj = nsnull;
if (NS_SUCCEEDED(acc->GetNativeInterface(&atkObj)))
return atkObj;
}
return nsnull;
}
#endif /* MOZ_ACCESSIBILITY_ATK */
/* static */
nsresult
EmbedPrivate::RegisterAppComponents(void)
{
nsCOMPtr<nsIComponentRegistrar> cr;
nsresult rv = NS_GetComponentRegistrar(getter_AddRefs(cr));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIComponentManager> cm;
rv = NS_GetComponentManager (getter_AddRefs (cm));
NS_ENSURE_SUCCESS (rv, rv);
#if 0
for (int i = 0; i < sNumAppComps; ++i) {
nsCOMPtr<nsIGenericFactory> componentFactory;
rv = NS_NewGenericFactory(getter_AddRefs(componentFactory),
&(sAppComps[i]));
if (NS_FAILED(rv)) {
NS_WARNING("Unable to create factory for component");
continue; // don't abort registering other components
}
rv = cr->RegisterFactory(sAppComps[i].mCID, sAppComps[i].mDescription,
sAppComps[i].mContractID, componentFactory);
NS_ASSERTION(NS_SUCCEEDED(rv), "Unable to register factory for component");
// Call the registration hook of the component, if any
if (sAppComps[i].mRegisterSelfProc) {
rv = sAppComps[i].mRegisterSelfProc(cm, nsnull, nsnull, nsnull,
&(sAppComps[i]));
NS_ASSERTION(NS_SUCCEEDED(rv), "Unable to self-register component");
}
}
#endif
return rv;
}
/* static */
void
EmbedPrivate::EnsureOffscreenWindow(void)
{
if (sOffscreenWindow)
return;
sOffscreenWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_realize(sOffscreenWindow);
sOffscreenFixed = gtk_fixed_new();
gtk_container_add(GTK_CONTAINER(sOffscreenWindow), sOffscreenFixed);
gtk_widget_realize(sOffscreenFixed);
}
/* static */
void
EmbedPrivate::DestroyOffscreenWindow(void)
{
if (!sOffscreenWindow)
return;
gtk_widget_destroy(sOffscreenWindow);
sOffscreenWindow = 0;
}
|
#include "stdafx.h"
#include "level.h"
level::level()
{
}
level::~level()
{
}
HRESULT level::init(void)
{
return E_NOTIMPL;
}
void level::release(void)
{
}
void level::renderFloor(void)
{
}
void level::renderWall(void)
{
}
|
#include "dds_uuid.h"
#include "sim_drill_objective_publisher.h"
CSimDrillObjectivePublisher::CSimDrillObjectivePublisher()
{
}
CSimDrillObjectivePublisher::~CSimDrillObjectivePublisher()
{
}
bool CSimDrillObjectivePublisher::Initialize()
{
CDdsUuid uuid;
uuid.GenerateUuid();
uuid.ExportUuid(m_pDataInstance->id);
return true;
}
void CSimDrillObjectivePublisher::SetId(const DataTypes::Uuid id)
{
if (m_pDataInstance != nullptr)
{
memcpy(m_pDataInstance->id, id, 16);
}
else
{
LOG_ERROR("Failed to set id on uninitialized sample");
}
}
void CSimDrillObjectivePublisher::SetRopLimit(const double ropLimit)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->ropLimit = ropLimit;
}
else
{
LOG_ERROR("Failed to set rop limit on uninitialized sample");
}
}
void CSimDrillObjectivePublisher::SetWobLimit(const double wobLimit)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->wobLimit = wobLimit;
}
else
{
LOG_ERROR("Failed to set wob limit on uninitialized sample");
}
}
void CSimDrillObjectivePublisher::SetDifferentialPressureLimit(const double differentialPressureLimit)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->differentialPressureLimit = differentialPressureLimit;
}
else
{
LOG_ERROR("Failed to set differential pressure limit on uninitialized sample");
}
}
void CSimDrillObjectivePublisher::SetTorqueLimit(const double torqueLimit)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->torqueLimit = torqueLimit;
}
else
{
LOG_ERROR("Failed to set torque limit on uninitialized sample");
}
}
void CSimDrillObjectivePublisher::SetRopMode(const bool ropMode)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->ropMode = ropMode;
}
else
{
LOG_ERROR("Failed to set rop mode on uninitialized sample");
}
}
void CSimDrillObjectivePublisher::SetWobMode(const bool wobMode)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->wobMode = wobMode;
}
else
{
LOG_ERROR("Failed to set wob mode on uninitialized sample");
}
}
void CSimDrillObjectivePublisher::SetDifferentialPressureMode(const bool differentialPressureMode)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->differentialPressureMode = differentialPressureMode;
}
else
{
LOG_ERROR("Failed to set differential pressure mode on uninitialized sample");
}
}
void CSimDrillObjectivePublisher::SetTorqueMode(const bool torqueMode)
{
if (m_pDataInstance != nullptr)
{
m_pDataInstance->torqueMode = torqueMode;
}
else
{
LOG_ERROR("Failed to set torque mode on uninitialized sample");
}
}
bool CSimDrillObjectivePublisher::PublishSample()
{
return Publish();
}
bool CSimDrillObjectivePublisher::Create(int32_t domain)
{
return TPublisher::Create(domain,
Simulation::SIM_AUTODRILLER_OBJECTIVE,
"EdgeBaseLibrary",
"EdgeBaseProfile");
}
|
#include "AbstractBaseController.h"
#include <QDebug>
#include <QFile>
namespace wpp
{
namespace qt
{
AbstractBaseController::AbstractBaseController()
: waitingRequestCount(0)
{
if ( !childControllers.empty() )
{
for ( QList<QObject *>::const_iterator it = childControllers.constBegin();
it != childControllers.constEnd() ; ++it )
{
AbstractBaseController *controller = dynamic_cast<AbstractBaseController *>( *it );
connect(controller,SIGNAL(waitingRequestCountChanged()),this,SLOT(updateWaitingRequestCount()));
}
}
}
void AbstractBaseController::clearQObjectStar(QVariant& var)
{
if ( var.isValid() && !var.isNull() )
{
QObject *obj = var.value<QObject *>();
delete obj;
obj = 0;
var = QVariant();
}
}
void AbstractBaseController::clearQObjectStarList(QList<QObject*>& list)
{
for ( QObject *obj : list )
{
qDebug() << "list[]:obj--" << (void*)obj << "::" << obj->objectName();
obj->deleteLater();
qDebug() << "list[]:obj--delete:" << (void*)obj;
}
list.clear();
}
void AbstractBaseController::clearQObjectStarList(QVariant& var)
{
if ( var.isValid() && !var.isNull() )
{
QList<QObject*> list = var.value< QList<QObject*> >();
qDebug() << "clearQObjectStarList: list length=" << list.length();
clearQObjectStarList(list);
/*for ( QObject *obj : list )
{
qDebug() << "list[]:obj--" << (void*)obj << "::" << obj->objectName();
delete obj;
qDebug() << "list[]:obj--delete:" << (void*)obj;
}*/
//qDebug() << "clearQObjectStarList: after for-loop, before qDeleteAll...";
//qDeleteAll( list );
//qDebug() << "clearQObjectStarList: after qDeleteAll...";
//list.clear();
qDebug() << "clearQObjectStarList: after clear()...";
var = QVariant::fromValue( list );
}
}
void AbstractBaseController::removeFiles(const QStringList& paths)
{
for ( QString path : paths )
{
QFile file(path);
file.setPermissions(QFile::ReadOther | QFile::WriteOther);
file.remove();
}
}
void AbstractBaseController::updateWaitingRequestCount()
{
qDebug() << "AbstractBaseController::updateWaitingRequestCount()...";
int count = 0;
for ( QList<QObject *>::const_iterator it = childControllers.constBegin();
it != childControllers.constEnd() ; ++it )
{
AbstractBaseController *controller = dynamic_cast<AbstractBaseController *>( *it );
count += controller->getWaitingRequestCount();
}
this->waitingRequestCount = count;
emit waitingRequestCountChanged();
}
void AbstractBaseController::clearChildControllers()
{
qDebug() << "AbstractBaseController::clearChildControllers()...";
if ( !childControllers.empty() )
{
for ( QList<QObject *>::const_iterator it = childControllers.constBegin();
it != childControllers.constEnd() ; ++it )
{
AbstractBaseController *controller = dynamic_cast<AbstractBaseController *>( *it );
disconnect(controller,SIGNAL(waitingRequestCountChanged()),this,SLOT(updateWaitingRequestCount()));
}
}
childControllers.clear();
updateWaitingRequestCount();
}
void AbstractBaseController::addChildController(AbstractBaseController *controller)
{
qDebug() << "AbstractBaseController::addChildController()...";
childControllers.push_back(controller);
connect(controller,SIGNAL(waitingRequestCountChanged()),this,SLOT(updateWaitingRequestCount()));
updateWaitingRequestCount();
}
}//namespace qt
}//namespace wpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ShrubberyCreationForm.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kwillum <kwillum@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/16 16:28:58 by kwillum #+# #+# */
/* Updated: 2021/01/22 17:42:47 by kwillum ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SHRUBBERYCREATIONFORM_HPP
# define SHRUBBERYCREATIONFORM_HPP
# include <iostream>
# include <string>
# include <fstream>
# include "Form.hpp"
class ShrubberyCreationForm : public Form
{
private:
const std::string _target;
static const std::string _tree;
ShrubberyCreationForm &operator=(const ShrubberyCreationForm &toCopy);
ShrubberyCreationForm();
class ShrubberyFormFileOpenException : std::exception
{
public:
virtual const char *what() const throw();
};
class ShrubberyFormWriteErrorException : std::exception
{
public:
virtual const char *what() const throw();
};
public:
ShrubberyCreationForm(const ShrubberyCreationForm &toCopy);
ShrubberyCreationForm(const std::string &target);
void execute(const Bureaucrat &b) const;
const std::string &getTartget() const;
virtual ~ShrubberyCreationForm();
};
#endif
|
/*
* service.cpp
* Copyright: 2018 Shanghai Yikun Electrical Engineering Co,Ltd
*/
#include "yikun_common/service/service.h"
#include <tf/tf.h>
#include <memory>
#include <nav_msgs/Odometry.h>
namespace yikun_common {
Service::Service(ros::NodeHandle &nh)
: nh_(nh),started_(false),global_frame_id_("map"),base_frame_id_("base_footprint"),
// sensor_frame_id_("uwb_link"),
vel_sub_(NULL),service_call_(NULL),move_base_superviser_(NULL)
{
private_nh_ = new ros::NodeHandle("~");
//服务地址
private_nh_->param("addr",addr_,std::string("0.0.0.0"));
int timesec;
private_nh_->param("timesec",timesec,60);
//世界坐标
private_nh_->param("global_frame_id",global_frame_id_,std::string("map"));
//小车坐标
private_nh_->param("base_frame_id",base_frame_id_,std::string("base_footprint"));
//uwb坐标
// private_nh_->param("sensor_frame_id",sensor_frame_id_,std::string("uwb_link"));
//movebase action
move_base_ = new _MoveBaseClient("move_base",true);
//service client
//手动位置校准
correct_client_ = private_nh_->serviceClient<std_srvs::Empty>("/request_adjust");
//路径设置请求接口定义
set_plan_ = private_nh_->serviceClient<yikun_cluster_msgs::SetPath>("/set_path");
//publisher
//amcl 位置初始化接口
set_pose_ = private_nh_->advertise<geometry_msgs::PoseWithCovarianceStamped>("/initialpose",1);
//小车速度控制接口
vel_pub_ = private_nh_->advertise<geometry_msgs::Twist>("/cmd_vel_mux/input/teleop",100);
// uwb_pose_pub_ = private_nh_->advertise<geometry_msgs::PoseWithCovarianceStamped>("uwb_pose",1000);
//UWB数据发布接口
uwb_pose_pub_ = private_nh_->advertise<nav_msgs::Odometry>("/odometry/uwb",10);
// e_stop_ = private_nh_->advertise<std_msgs::Bool>("/e_stop",1);
simple_goal_pub_ = private_nh_->advertise<geometry_msgs::PoseStamped>("/move_base_simple/goal",1);
plan_pub_ = private_nh_->advertise<nav_msgs::Path>("global_path",1);
//subcriber
//前往接口(WEB)
simple_goal_sub_ = private_nh_->subscribe<yikun_cluster_msgs::DockPose>("/yikun/simple_goal",1,boost::bind(&Service::simpleGoal,this,_1));
//service server
//设置初始位置(WEB)
set_pose_server_ = private_nh_->advertiseService("/yikun/set_pose",&Service::setPose,this);
//手动位置校准(WEB)
correct_server_ = private_nh_->advertiseService("/yikun/correct_location",&Service::correctLocation,this);
//timeout
timeout_.tv_sec = timesec;
timeout_.tv_usec = 0;
}
Service::~Service()
{
//线程销毁
vel_sub_->interrupt();
uwb_sub_->interrupt();
service_call_->interrupt();
path_gen_service_->interrupt();
move_base_superviser_->interrupt();
vel_sub_->join();
uwb_sub_->join();
service_call_->join();
path_gen_service_->join();
move_base_superviser_->join();
delete service_call_,path_gen_service_;
delete move_base_superviser_,
delete vel_sub_,uwb_sub_;
vel_sub_ = uwb_sub_ = service_call_ = path_gen_service_ = move_base_superviser_ = NULL;
}
void Service::start()
{
if(started_) {
std::perror("is running");
return;
}
//线程初始化
move_base_superviser_ = new boost::thread(boost::bind(&Service::movebaseSuperviser,this));
vel_sub_ = new boost::thread(boost::bind(&Service::velocitySubcriber,this));
uwb_sub_ = new boost::thread(boost::bind(&Service::uwbPoseSubcriber,this));
service_call_ = new boost::thread(boost::bind(&Service::goalServiceServer,this));
// path_gen_service_ = new boost::thread(boost::bind(&Service::setPathServer,this));
path_gen_service_ = new boost::thread(boost::bind(&Service::PathSubcriber,this));
started_ = true;
}
void Service::stop()
{
if(started_) {
return;
}
//线程销毁
vel_sub_->interrupt();
uwb_sub_->interrupt();
service_call_->interrupt();
path_gen_service_->interrupt();
move_base_superviser_->interrupt();
vel_sub_->join();
uwb_sub_->join();
service_call_->join();
path_gen_service_->join();
move_base_superviser_->join();
delete service_call_,path_gen_service_;
delete move_base_superviser_,
delete vel_sub_,uwb_sub_;
vel_sub_ = uwb_sub_ = service_call_ = path_gen_service_ = move_base_superviser_ = NULL;
}
void Service::goalServiceServer()
{
boost::this_thread::interruption_point();
constexpr int listen_port = TCP_PORT;
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1)
{
std::perror("socket");
return;
}
//timeout
//设置请求超时
if(setsockopt(sock,SOL_SOCKET,SO_SNDTIMEO,(const char*)&timeout_,sizeof(timeout_)) == -1)
return;
if(setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,(const char*)&timeout_,sizeof(timeout_)) == -1)
return;
sockaddr_in client;
socklen_t len = sizeof(client);
sockaddr_in addr;
std::memset(&addr, 0, sizeof(sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(listen_port);
addr.sin_addr.s_addr = inet_addr(addr_.data());
int ret = bind(sock, (sockaddr *)&addr, sizeof(addr));
if (ret == -1)
{
std::perror("bind");
goto error;
}
// std::cout<<__func__<<" bind addr "<<addr_<<std::endl;
ret = listen(sock, 1);
if (ret == -1)
{
std::perror("listen");
goto error;
}
while (nh_.ok())
{
// get connect
// std::cout << "Waiting tcp access..." << std::endl;
// boost::unique_lock<boost::recursive_mutex> lock(recursive_mutex_);
//等待连接请求
int *client_sock = new int();
*client_sock = accept(sock, reinterpret_cast<sockaddr *>(&client), &len);
if (*client_sock == -1)
{
std::perror("accept goal");
continue;
}
//just one thread
_PoseStamped pose;
std::memset(&pose,0,sizeof(_PoseStamped));
ssize_t n = recv(*client_sock, &pose, sizeof(_PoseStamped), 0); //获取位置点数据
if(n < 0 && errno == EAGAIN){
std::perror("recv");
continue;
}
// ROS_INFO("%s,%.4f,%.4f,%.4f",pose.frame_id,pose.orientation.w,pose.position.x,pose.stamp);
//request
if(this->sendGoal(pose)) {
pose.ack = ACK_SUCCEED;
} else {
pose.ack = ACK_FAILED;
}
pose.stamp = ros::Time::now().toSec();
//response
n = send(*client_sock, &pose, sizeof(_PoseStamped), 0); //发送响应数据
if(n < 0 && errno == EAGAIN){
std::perror("write");
continue;
}
//multithread
//.....
}
//end
boost::this_thread::interruption_enabled();
return;
error:
close(sock);
boost::this_thread::interruption_enabled();
return;
}
void Service::setPathServer()
{
boost::this_thread::interruption_point();
constexpr int listen_port = PATH_PORT;
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == -1)
{
std::perror("socket");
return;
}
//timeout
struct timeval timeout;
timeout.tv_sec = 600;
timeout.tv_usec = 0;
if(setsockopt(sock,SOL_SOCKET,SO_SNDTIMEO,(const char*)&timeout,sizeof(timeout_)) == -1)
return;
if(setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,(const char*)&timeout,sizeof(timeout_)) == -1)
return;
sockaddr_in client;
socklen_t len = sizeof(client);
sockaddr_in addr;
std::memset(&addr, 0, sizeof(sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(listen_port);
addr.sin_addr.s_addr = inet_addr(addr_.data());
int ret = bind(sock, (sockaddr *)&addr, sizeof(addr));
if (ret == -1)
{
std::perror("bind");
goto error;
}
// std::cout<<__func__<<" bind addr "<<addr_<<std::endl;
ret = listen(sock, 1);
if (ret == -1)
{
std::perror("listen");
goto error;
}
while (nh_.ok())
{
_Paths paths;
// get connect
int *client_sock = new int();
*client_sock = accept(sock, reinterpret_cast<sockaddr *>(&client), &len);
if (*client_sock == -1)
{
std::perror("accept path");
continue;
}
//just one thread
std::memset(&paths,0,sizeof(_Paths));
ssize_t n = recv(*client_sock, &paths, sizeof(_Paths), 0);
if(n < 0 && errno == EAGAIN){
std::perror("recv");
continue;
}
//request
if(this->setPath(paths.paths)) {
std::memset(&paths,0,sizeof(_Paths));
paths.ack = ACK_SUCCEED;
} else {
std::memset(&paths,0,sizeof(_Paths));
paths.ack = ACK_FAILED;
}
//response
n = send(*client_sock, &paths, sizeof(_Paths), 0);
if(n < 0 && errno == EAGAIN){
std::perror("write");
continue;
}
std::memset(&paths,0,sizeof(_Paths));
//multithread
//.....
}
//end
boost::this_thread::interruption_enabled();
return;
error:
close(sock);
boost::this_thread::interruption_enabled();
return;
}
void Service::velocitySubcriber()
{
boost::this_thread::interruption_point();
constexpr int listen_port = UDP_PORT;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == -1)
{
std::perror("socket");
return;
}
//timeout
// if(setsockopt(sock,SOL_SOCKET,SO_SNDTIMEO,(const char*)&timeout_,sizeof(timeout_)) == -1)
// return;
// if(setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,(const char*)&timeout_,sizeof(timeout_)) == -1)
// return;
sockaddr_in client;
socklen_t len = sizeof(client);
sockaddr_in addr;
std::memset(&addr, 0, sizeof(sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(listen_port);
addr.sin_addr.s_addr = inet_addr(addr_.data());
int ret = bind(sock, (sockaddr *)&addr, sizeof(addr));
if (ret == -1)
{
std::perror("bind");
// goto error;
return;
}
while (nh_.ok())
{
// get connect
// std::cout << "Waiting udp access..." << std::endl;
// boost::unique_lock<boost::recursive_mutex> lock(recursive_mutex_);
int *client_sock = new int();
_twist twist;
std::memset(&twist,0,sizeof(_twist));
*client_sock = recvfrom(sock, &twist, sizeof(_twist), 0,reinterpret_cast<sockaddr *>(&client), &len);
if (*client_sock == -1 && errno == EAGAIN)
{
std::perror("recv");
continue;
}
//response
geometry_msgs::Twist vel;
vel.linear.x = twist.linear_x;
vel.angular.z = twist.angular_z;
// std::cout<<twist.linear_x<<"\t"<<twist.angular_z<<std::endl;
vel_pub_.publish(vel);
}
//end
boost::this_thread::interruption_enabled();
return;
//error:
// close(sock);
// boost::this_thread::interruption_enabled();
// return;
}
void Service::PathSubcriber()
{
boost::this_thread::interruption_point();
constexpr int listen_port = PATH_PORT;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == -1)
{
std::perror("socket");
return;
}
sockaddr_in client;
socklen_t len = sizeof(client);
sockaddr_in addr;
std::memset(&addr, 0, sizeof(sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(listen_port);
addr.sin_addr.s_addr = inet_addr(addr_.data());
int ret = bind(sock, (sockaddr *)&addr, sizeof(addr));
if (ret == -1)
{
std::perror("bind");
// goto error;
return;
}
while (nh_.ok())
{
// get connect
int *client_sock = new int();
_Paths path;
std::memset(&path,0,sizeof(_Paths));
*client_sock = recvfrom(sock, &path, sizeof(_Paths), 0,reinterpret_cast<sockaddr *>(&client), &len);
if (*client_sock == -1 && errno == EAGAIN)
{
std::perror("recv");
continue;
}
//request
if(this->setPath(path.paths)) {
std::memset(&path,0,sizeof(_Paths));
path.ack = ACK_SUCCEED;
} else {
std::memset(&path,0,sizeof(_Paths));
path.ack = ACK_FAILED;
}
//no response
}
//end
boost::this_thread::interruption_enabled();
return;
}
void Service::uwbPoseSubcriber()
{
boost::this_thread::interruption_point();
constexpr int listen_port = UWB_PORT;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == -1)
{
std::perror("socket");
return;
}
//timeout
// if(setsockopt(sock,SOL_SOCKET,SO_SNDTIMEO,(const char*)&timeout_,sizeof(timeout_)) == -1)
// return;
// if(setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,(const char*)&timeout_,sizeof(timeout_)) == -1)
// return;
sockaddr_in client;
socklen_t len = sizeof(client);
sockaddr_in addr;
std::memset(&addr, 0, sizeof(sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(listen_port);
addr.sin_addr.s_addr = inet_addr(addr_.data());
int ret = bind(sock, (sockaddr *)&addr, sizeof(addr));
if (ret == -1)
{
std::perror("bind");
// goto error;
return;
}
while (nh_.ok())
{
// get connect
// std::cout << "Waiting udp access..." << std::endl;
// boost::unique_lock<boost::recursive_mutex> lock(recursive_mutex_);
int *client_sock = new int();
_PoseWithCovarianceStamped pose;
std::memset(&pose,0,sizeof(_PoseWithCovarianceStamped));
*client_sock = recvfrom(sock, &pose, sizeof(_PoseWithCovarianceStamped), 0,reinterpret_cast<sockaddr *>(&client), &len);
if (*client_sock == -1 && errno == EAGAIN)
{
std::perror("recv");
continue;
}
//response
// geometry_msgs::PoseWithCovarianceStamped pose_msg;
nav_msgs::Odometry uwb_odom;
ros::Time time;
time.fromSec(pose.stamp);
uwb_odom.header.stamp = time;
uwb_odom.header.frame_id = pose.frame_id;
uwb_odom.child_frame_id = base_frame_id_;
// uwb_odom.child_frame_id = sensor_frame_id_;
uwb_odom.pose.pose.position.x = pose.position.x;
uwb_odom.pose.pose.position.y = pose.position.y;
uwb_odom.pose.pose.position.z = pose.position.z;
uwb_odom.pose.pose.orientation.w = pose.orientation.w;
uwb_odom.pose.pose.orientation.x = pose.orientation.x;
uwb_odom.pose.pose.orientation.y = pose.orientation.y;
uwb_odom.pose.pose.orientation.z = pose.orientation.z;
for(int i=0;i<36;i++) {
uwb_odom.pose.covariance[i] = pose.covariance[i];
}
uwb_pose_pub_.publish(uwb_odom);
}
//end
boost::this_thread::interruption_enabled();
return;
//error:
// close(sock);
// boost::this_thread::interruption_enabled();
// return;
}
bool Service::getPath(const char *p,std::vector<geometry_msgs::PoseStamped> &path)
{
path.clear();
//路径解析,将路径转化为标准路径格式
std::string pathstr = p;
std::vector<std::string> points;
if(pathstr.find(';') == std::string::npos)
return false;
boost::split(points,pathstr,boost::is_any_of(";"));
for(std::string point : points)
{
std::vector<std::string> index;
geometry_msgs::PoseStamped pose;
if(point.find(',') == std::string::npos)
return true;
boost::split(index,point,boost::is_any_of(","));
pose.header.frame_id = global_frame_id_;
pose.header.stamp = ros::Time::now();
//(x,y)根据实际路径文件赋值
pose.pose.position.x = atof(index[2].c_str())*0.01; //x
pose.pose.position.y = atof(index[1].c_str())*0.01; //y
//姿态初始化,UWB数据中无姿态
pose.pose.orientation.x = 0;
pose.pose.orientation.y = 0;
pose.pose.orientation.z = 0;
pose.pose.orientation.w = 1;
path.push_back(pose);
}
return true;
}
bool Service::setPath(const char *p)
{
std::vector<geometry_msgs::PoseStamped> path;
if(getPath(p,path)) {
this->publishPlan(path,plan_pub_);
}
}
bool Service::sendGoal(const _PoseStamped &pos)
{
if(!is_navigation_) {
sleep(5);
return false;
}
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.header.frame_id = pos.frame_id;
goal.target_pose.header.stamp.sec = pos.stamp;
goal.target_pose.pose.position.x = pos.position.x;
goal.target_pose.pose.position.y = pos.position.y;
goal.target_pose.pose.position.z = pos.position.z;
goal.target_pose.pose.orientation.w = pos.orientation.w;
goal.target_pose.pose.orientation.x = pos.orientation.x;
goal.target_pose.pose.orientation.y = pos.orientation.y;
goal.target_pose.pose.orientation.z = pos.orientation.z;
move_base_->sendGoal(goal);
move_base_->waitForResult();
if(move_base_->getState() == actionlib::SimpleClientGoalState::SUCCEEDED) {
return true;
} else {
return false;
}
}
void Service::movebaseSuperviser()
{
boost::this_thread::interruption_point();
while(nh_.ok())
{
is_navigation_ = move_base_->waitForServer(ros::Duration(1.0)); //检查Move Base连接
}
//end
boost::this_thread::interruption_enabled();
}
bool Service::correctLocation(std_srvs::EmptyRequest &req, std_srvs::EmptyResponse &res)
{
//if robot state is navigation
if(is_navigation_)
{
std_srvs::Empty call;
for(int i = 0;i<10;i++)//attempting to request 10 times
{
correct_client_.call(call);//request amcl
ros::Duration(0.1).sleep();
}
return true;
}
else {
ROS_ERROR_STREAM("MoveBase is shutdown");
return false;
}
}
bool Service::setPose(yikun_cluster_msgs::SetPoseRequest &req, yikun_cluster_msgs::SetPoseResponse &res)
{
if(!is_navigation_) {
res.result = 0;
ROS_ERROR_STREAM("MoveBase is shutdown");
}
geometry_msgs::PoseWithCovarianceStamped pos;
pos.header.frame_id = "map";
pos.header.stamp = ros::Time::now();
pos.pose.pose.position.x = req.x;
pos.pose.pose.position.y = req.y;
tf::Quaternion q = tf::createQuaternionFromYaw((double)(req.theta*M_PI/180));
pos.pose.pose.orientation.w = q.getW();
pos.pose.pose.orientation.x = q.getX();
pos.pose.pose.orientation.y = q.getY();
pos.pose.pose.orientation.z = q.getZ();
pos.pose.covariance[6*0+0] = 0.5 * 0.5;
pos.pose.covariance[6*1+1] = 0.5 * 0.5;
pos.pose.covariance[6*5+5] = M_PI/12.0 * M_PI/12.0;
set_pose_.publish(pos);
ros::Duration(0.1).sleep();//sleep
res.result = 1;
return true;
}
void Service::simpleGoal(yikun_cluster_msgs::DockPoseConstPtr msg)
{
if(!is_navigation_) {
ROS_ERROR_STREAM("MoveBase is shutdown");
}
geometry_msgs::PoseStamped pose;
pose.header.stamp = ros::Time::now();
pose.header.frame_id = "map";
pose.pose.position.x = msg->x;
pose.pose.position.y = msg->y;
tf::Quaternion q = tf::createQuaternionFromYaw((double)(msg->theta*M_PI/180));
pose.pose.orientation.w = q.getW();
pose.pose.orientation.x = q.getX();
pose.pose.orientation.y = q.getY();
pose.pose.orientation.z = q.getZ();
simple_goal_pub_.publish(pose);
ros::Duration(0.1).sleep();//sleep
}
void *Service::moveto(void *arg)
{
ROS_INFO_STREAM("service call begin");
int *client_sockp = static_cast<int *>(arg);
int sock = *client_sockp;
delete client_sockp;
_PoseStamped *pos = (_PoseStamped*)malloc(sizeof(_PoseStamped));
int len = sizeof(pos);
char tmp[len];
if(true) {
ssize_t n = recv(sock, tmp, len, 0);
if(n < 0){
std::perror("recv");
return nullptr;
}
memcpy(pos,tmp,len);
pos->ack = ACK_SUCCEED;
memset(tmp,0,len);
memcpy(tmp,pos,len);
n = write(sock, tmp, sizeof(tmp));
if(n < 0){
std::perror("write");
return nullptr;
}
}
if (close(sock) < 0)
{
std::perror("close");
return nullptr;
}
ROS_INFO_STREAM("service call end");
return nullptr;
}
void Service::publishPlan(const std::vector<geometry_msgs::PoseStamped>& path, const ros::Publisher& pub)
{
//given an empty path we won't do anything
if(path.empty())
return;
//create a path message
nav_msgs::Path gui_path;
gui_path.poses.resize(path.size());
gui_path.header.frame_id = path[0].header.frame_id;
gui_path.header.stamp = path[0].header.stamp;
// Extract the plan in world co-ordinates, we assume the path is all in the same frame
for(unsigned int i=0; i < path.size(); i++){
gui_path.poses[i] = path[i];
}
yikun_cluster_msgs::SetPath client;
client.request.path = gui_path;
if(!set_plan_.call(client))
ROS_WARN_STREAM("set plan");
pub.publish(gui_path);
}
}//namespace
|
// DisplayDeviceFinger.h: interface for the DisplayDeviceFinger class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_DISPLAYDEVICEFINGER_H__2023312B_2262_4CED_92C0_3CF406645864__INCLUDED_)
#define AFX_DISPLAYDEVICEFINGER_H__2023312B_2262_4CED_92C0_3CF406645864__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "TactileArray.h"
#define FINGER_ARRAY_SIZE_X 1
#define FINGER_ARRAY_SIZE_Y 3
class DisplayDeviceFinger : public TactileArray
{
public:
DisplayDeviceFinger(int a_portNum);
virtual ~DisplayDeviceFinger();
int m_array[FINGER_ARRAY_SIZE_X][FINGER_ARRAY_SIZE_Y];
void setActReset()
{
setIntensityAll(0);
}
void setActFinger(double a_actY);
};
#endif // !defined(AFX_DISPLAYDEVICEFINGER_H__2023312B_2262_4CED_92C0_3CF406645864__INCLUDED_)
|
/*!
* @author Nicholas Kidd
*/
#include "wali/Common.hpp"
#include "wali/DefaultWorklist.hpp"
#include "wali/wfa/WFA.hpp"
#include "wali/wfa/State.hpp"
#include "wali/wfa/TransFunctor.hpp"
#include "wali/wfa/Trans.hpp"
#include "wali/wfa/WeightMaker.hpp"
#include "wali/regex/AllRegex.hpp"
#include "wali/wpds/GenKeySource.hpp"
#include "wali/wfa/DeterminizeWeightGen.hpp"
#include "wali/wpds/WPDS.hpp"
#include "wali/wpds/fwpds/FWPDS.hpp"
#include "wali/wpds/fwpds/LazyTrans.hpp"
#include "wali/graph/RegExp.hpp"
#include "wali/util/ConfigurationVar.hpp"
#include <algorithm>
#include <iostream>
#include <vector>
#include <stack>
#include <iterator>
#include <fstream>
#define FOR_EACH_STATE(name) \
State* name; \
state_map_t::iterator name##it = state_map.begin(); \
state_map_t::iterator name##itEND = state_map.end(); \
for( ; name##it != name##itEND && (0 != (name = name##it->second)) ; name##it++ )
#define FOR_EACH_FINAL_STATE(name) \
State* name; \
std::set< Key >::iterator name##it = F.begin(); \
std::set< Key >::iterator name##itEND = F.end(); \
for( ; name##it != name##itEND && (0 != (name = getState(*name##it))) ; name##it++ )
namespace wali
{
namespace wfa
{
const std::string WFA::XMLTag("WFA");
const std::string WFA::XMLQueryTag("query");
const std::string WFA::XMLInorderTag("INORDER");
const std::string WFA::XMLReverseTag("REVERSE");
bool is_epsilon_transition(ITrans const * trans)
{
return trans->stack() == WALI_EPSILON;
}
bool is_any_transition(ITrans const * trans)
{
(void) trans;
return true;
}
WFA::WFA( query_t q, progress_t prog )
: init_state( WALI_EPSILON )
, query(q)
, generation(0)
, progress(prog)
, defaultPathSummaryImplementation(globalDefaultPathSummaryImplementation)
, defaultPathSummaryFwpdsDirection(globalDefaultPathSummaryFwpdsDirection)
{
if( query == MAX ) {
*waliErr << "[WARNING] Invalid WFA::query. Resetting to INORDER.\n";
query = INORDER;
}
}
WFA::WFA( const WFA & rhs ) : Printable()
{
operator=(rhs);
}
WFA& WFA::operator=( const WFA & rhs )
{
if( this != &rhs )
{
clear();
// Copy important state information
init_state = rhs.init_state;
F = rhs.F;
query = rhs.query;
progress = rhs.progress;
// Be sure to copy the state_map. Otherwise,
// some states that are in rhs but not actually apart
// of a transition will be lost.
state_map_t::const_iterator it = rhs.state_map.begin();
for( ; it != rhs.state_map.end(); it++ ) {
// FIXME: why is this ->zero()? --EED 5/11/2012
addState( it->first, it->second->weight()->zero() );
if (!it->second->acceptWeight()->equal(it->second->acceptWeight()->zero())) {
getState(it->first)->acceptWeight() = it->second->acceptWeight();
}
}
// This will populate all maps
TransCopier copier(*this);
rhs.for_each( copier );
generation = rhs.generation;
defaultPathSummaryImplementation = rhs.defaultPathSummaryImplementation;
defaultPathSummaryFwpdsDirection = rhs.defaultPathSummaryFwpdsDirection;
}
return *this;
}
WFA::~WFA()
{
clear();
}
void WFA::clear()
{
/* Must manually delete all Trans objects. If reference
* counting is used this code can be removed
*/
TransDeleter td;
for_each(td);
/* Must manually delete all State objects. If reference
* counting is used this code can be removed
*/
state_map_t::iterator it = state_map.begin();
state_map_t::iterator itEND = state_map.end();
for( ; it != itEND ; it++ )
{
delete it->second;
it->second = 0;
}
for (std::set<State*>::const_iterator s = deleted_states.begin();
s != deleted_states.end(); ++s)
{
delete *s;
}
deleted_states.clear();
/* Clear all of the maps to release references to stale
* objects */
kpmap.clear();
eps_map.clear();
state_map.clear();
F.clear();
Q.clear();
init_state = WALI_EPSILON;
}
//!
// @brief set initial state
//
Key WFA::set_initial_state( Key key )
{
return setInitialState(key);
}
//!
// @brief set initial state
//
Key WFA::setInitialState( Key key )
{
assert( getState(key) != NULL );
Key isold = init_state;
// TODO : Add debug check to verify key exists
init_state = key;
return isold;
}
//!
// Add parameter key to the set of final states
//
void WFA::add_final_state( Key key )
{
assert( getState(key) != NULL );
F.insert(key);
}
//!
// Add parameter key to the set of final states
//
void WFA::addFinalState( Key key )
{
assert( getState(key) != NULL );
addFinalState(key, getSomeWeight()->one());
}
void WFA::addFinalState(Key key, sem_elem_t accept_weight)
{
assert( getState(key) != NULL );
F.insert(key);
getState(key)->acceptWeight() = accept_weight;
}
//!
// Return true if parameter key is a final state
//
bool WFA::isFinalState( Key key ) const
{
return (F.find(key) != F.end());
}
//
// @brief Return the initial state
//
Key WFA::initial_state() const
{
return init_state;
}
//
// @brief Return the initial state
//
Key WFA::getInitialState() const
{
return init_state;
}
//
// Test if param key is the initial state.
//
bool WFA::isInitialState( Key key ) const
{
return key == init_state;
}
//
// Set the query
//
WFA::query_t WFA::setQuery( WFA::query_t newQuery )
{
query_t old = query;
query = newQuery;
return old;
}
//
// get the query
//
WFA::query_t WFA::getQuery() const
{
return query;
}
//
// get the current generation
//
size_t WFA::getGeneration() const
{
return generation;
}
//
// Set the generation
//
void WFA::setGeneration(size_t g)
{
generation = g;
}
//
// Get some weight from the WFA, if it is non-empty
// If the WFA is empty, return NULL
//
sem_elem_t WFA::getSomeWeight() const{
kp_map_t::const_iterator it = kpmap.begin();
while(it != kpmap.end()) {
const TransSet &tset = it->second;
TransSet::const_iterator it2 = tset.begin();
if(it2 != tset.end()) {
return (*it2)->weight();
}
it ++;
}
assert(Q.size() > 0u);
Key any_state = *Q.begin();
return getState(any_state)->weight();
}
//!
//! @brief add trans (p,g,q,se) to WFA
//! Default creates a basic Trans object.
//!
std::pair<ITrans const *, bool>
WFA::addTrans(
Key p,
Key g,
Key q,
sem_elem_t se )
{
return addTrans( new Trans(p,g,q,se) );
}
//!
//! @brief add ITrans*t to WFA
//! Takes care of adding states and calling insert. This
//! method (actually insert) assumes ownership of the memory
//! pointed to by the ITrans* t.
//!
std::pair<ITrans const *, bool>
WFA::addTrans( ITrans * t )
{
//t->print( *waliErr << "\tInserting Trans" ) << std::endl;
return insert( t );
}
//
// Erase a trans from the WFA maps
// Returns the erased trans
//
ITrans * WFA::eraseTransFromMaps(
Key from,
Key stack,
Key to )
{
// Remove from kpmap
ITrans* tKp = eraseTransFromKpMap(from,stack,to);
if( tKp != NULL )
{
ITrans* tEps = eraseTransFromEpsMap(tKp);
{ // BEGIN DEBUGGING
if( tEps != NULL )
assert( tKp == tEps );
} // END DEBUGGING
}
return tKp;
}
//
// Erase a trans
// Must remove from kpmap, eps_map, State('from')
//
void WFA::erase(
Key from,
Key stack,
Key to )
{
// Remove from maps
ITrans* t = eraseTransFromMaps(from,stack,to);
State* state = state_map.find(from)->second;
state->eraseTrans(t);
delete t;
}
namespace details {
class TransRemover
: public TransFunctor
{
std::vector<ITrans*> to_remove_;
Key the_state_;
public:
TransRemover(Key the_state)
: the_state_(the_state)
{}
virtual void operator() (ITrans* t) {
if (t->from() == the_state_ || t->to() == the_state_) {
to_remove_.push_back(t);
}
}
void removeFrom(WFA * wfa) const {
for (std::vector<ITrans*>::const_iterator iter = to_remove_.begin();
iter != to_remove_.end(); ++iter)
{
wfa->erase((*iter)->from(), (*iter)->stack(), (*iter)->to());
}
}
};
}
//
// Removes State q from the WFA and any transitions leading
// to and from q.
//
bool WFA::eraseState(
Key q
)
{
state_map_t::iterator it = state_map.find(q);
if( it == state_map.end() ) {
return false;
}
return eraseState( it->second );
}
//
// Finds Trans(p,g,q). Invokes copy constructor on parameter t.
// Returns true if find was successful.
//
bool WFA::find(
Key p,
Key g,
Key q,
Trans & t ) const
{
ITrans const * itrans = find(p,g,q);
if(itrans != 0) {
t = *itrans;
return true;
}
return false;
}
//
// Finds Trans(p,g,q) and returns a pointer to it
// (null if not found)
// This should only be used by friend classes because
// it exposes a pointer to inside the WFA
//
ITrans* WFA::find(
Key p,
Key g,
Key q)
{
WFA const * const_this = this;
ITrans const * trans = const_this->find(p,g,q);
return const_cast<ITrans*>(trans);
}
ITrans const * WFA::find(
Key p,
Key g,
Key q) const
{
KeyPair kp(p,g);
kp_map_t::const_iterator it = kpmap.find(kp);
if( it != kpmap.end() )
{
TransSet const & transSet = it->second;
TransSet::const_iterator tsit= transSet.find(p,g,q);
if( tsit != transSet.end() ) {
ITrans const * itrans = *tsit;
return itrans;
}
}
return 0;
}
namespace details {
template<typename FunctorType>
void for_each_mutable(WFA::state_map_t & state_map,
FunctorType & func)
{
WFA::state_map_t::iterator it = state_map.begin();
WFA::state_map_t::iterator itEND = state_map.end();
for( ; it != itEND ; it++ )
{
State* st = it->second;
TransSet & transSet = st->getTransSet();
transSet.each(func);
}
}
template<typename FunctorType>
void for_each_const(WFA::state_map_t const & state_map,
FunctorType & func)
{
WFA::state_map_t::const_iterator it = state_map.begin();
WFA::state_map_t::const_iterator itEND = state_map.end();
for( ; it != itEND ; it++ )
{
const State* st = it->second;
const TransSet & transSet = st->getTransSet();
transSet.each(func);
}
}
}
void WFA::for_each( ConstTransFunctor & tf ) const
{
details::for_each_const(state_map, tf);
}
void WFA::for_each( TransFunctor& tf )
{
details::for_each_mutable(state_map, tf);
}
void WFA::for_each( boost::function<void(ITrans * t)> & tf )
{
details::for_each_mutable(state_map, tf);
}
void WFA::for_each( boost::function<void(ITrans const * t)> & tf ) const
{
details::for_each_const(state_map, tf);
}
void WFA::duplicateStates(std::set<Key> &st, WFA &output) const {
// Create a map from state to their renamed counterpart
std::map< Key, Key > dup;
std::set< Key >::const_iterator it;
for(it = st.begin(); it != st.end(); it++) {
Key s = *it;
Key sprime = getKey(key_src_t(new wpds::GenKeySource(getGeneration(), s)));
dup[s] = sprime;
}
// Use TransDuplicator to put in the right transitions
TransDuplicator td(output, dup);
for_each(td);
// Set initial and final states in output to be the same as input
output.setInitialState(getInitialState());
for(it = F.begin(); it != F.end(); it++) {
output.addFinalState(*it);
}
// Set generation
output.setGeneration(getGeneration() + 1);
}
/*!
* Intersect this with parameter fa. This is a wrapper
* for intersect( WeightMaker&,WFA& ) that passes
* the WeightMaker KeepBoth.
*
* @see WeightMaker
*/
WFA WFA::intersect( WFA const & fa ) const
{
KeepBoth wmaker;
return intersect(wmaker,fa);
}
void WFA::intersect( WFA const & fa, WFA& dest ) const
{
KeepBoth wmaker;
intersect(wmaker,fa,dest);
}
/*
* Intersect this and fa, returning the result
*/
WFA WFA::intersect( WeightMaker& wmaker , WFA const & fa ) const
{
WFA dest;
intersect(wmaker,fa,dest);
return dest;
}
void WFA::intersect(
WeightMaker& wmaker
, WFA const & fa
, WFA& dest ) const
{
intersect_worklist(wmaker, fa, dest);
}
namespace details
{
void
maybe_add_state(WFA & dest,
std::vector<KeyPair> & worklist,
WFA const & left,
WFA const & right,
WeightMaker & wmaker,
sem_elem_t zero,
Key target_key,
KeyPair target_pair)
{
if (dest.getStates().count(target_key) == 0) {
sem_elem_t
state_weight = wmaker.make_weight(left.getState(target_pair.first)->weight(),
right.getState(target_pair.second)->weight()),
accept_weight = wmaker.make_weight(left.getState(target_pair.first)->acceptWeight(),
right.getState(target_pair.second)->acceptWeight());
if (state_weight.get_ptr() == NULL) {
state_weight = zero;
}
dest.addState(target_key, state_weight);
worklist.push_back(target_pair);
if (left.isFinalState(target_pair.first)
&& right.isFinalState(target_pair.second))
{
dest.addFinalState(target_key, accept_weight);
}
}
}
void
handle_transition(WFA & dest,
std::vector<KeyPair> & worklist,
WeightMaker & wmaker,
sem_elem_t zero,
ITrans const * left_trans,
ITrans const * right_trans,
WFA const & left,
WFA const & right)
{
Key source_key = getKey(left_trans->from(), right_trans->from());
Key this_mid = left_trans->to();
Key fa_mid = right_trans->to();
Key symbol = left_trans->stack();
assert(symbol == right_trans->stack());
// *sym_iter
// - - - > o ---------> o
// source_... ..._mid
KeyPair target_pair(this_mid, fa_mid);
Key target_key = getKey(target_pair.first, target_pair.second);
maybe_add_state(dest, worklist,
left, right,
wmaker, zero,
target_key, target_pair);
sem_elem_t
final_weight = wmaker.make_weight(left_trans, right_trans);
dest.addTrans(source_key, symbol, target_key, final_weight);
}
}
//
// Intersect this and fa, storing the result in dest
// TODO: Note: if this == dest there might be a problem
//
void WFA::intersect_worklist(
WeightMaker& wmaker
, WFA const & fa
, WFA& dest ) const
{
dest.clear();
dest.setQuery(this->getQuery());
sem_elem_t zero = wmaker.make_weight(this->getSomeWeight()->one(),
fa.getSomeWeight()->one())->zero();
// Sigh
std::set<Key> alphabet;
for(kp_map_t::const_iterator iter = kpmap.begin();
iter != kpmap.end(); ++iter)
{
alphabet.insert(iter->first.second);
}
alphabet.insert(WALI_EPSILON);
// Siiiiiiiigh. (nc = non-const)
WFA * this_nc = const_cast<WFA*>(this);
WFA * fa_nc = const_cast<WFA*>(&fa);
// Now start the actual intersection bit.
std::vector<KeyPair> worklist;
Key initial_key = getKey(this->getInitialState(), fa.getInitialState());
KeyPair initial_pair(this->getInitialState(), fa.getInitialState());
details::maybe_add_state(dest, worklist,
*this, fa,
wmaker, zero,
initial_key, initial_pair);
dest.setInitialState(initial_key);
// Begin the worklist processing
while (!worklist.empty()) {
KeyPair source_pair = worklist.back();
worklist.pop_back();
for (std::set<Key>::const_iterator sym_iter = alphabet.begin();
sym_iter != alphabet.end(); ++sym_iter)
{
TransSet
this_outgoing = this_nc->match(source_pair.first, *sym_iter),
fa_outgoing = fa_nc->match(source_pair.second, *sym_iter);
ITrans
* left_no_motion = NULL,
* right_no_motion = NULL;
if (*sym_iter == WALI_EPSILON) {
// One automaton or the other can not move
left_no_motion = new Trans(source_pair.first, WALI_EPSILON,
source_pair.first, this->getSomeWeight()->one());
right_no_motion = new Trans(source_pair.second, WALI_EPSILON,
source_pair.second, fa.getSomeWeight()->one());
// Will fail if there is already an epsilon self
// loop. (Non-trivial cycles should be OK.)
assert(this_outgoing.find(left_no_motion) == this_outgoing.end());
assert(fa_outgoing.find(right_no_motion) == fa_outgoing.end());
this_outgoing.insert(left_no_motion);
fa_outgoing.insert(right_no_motion);
}
for (TransSet::const_iterator this_trans_iter = this_outgoing.begin();
this_trans_iter != this_outgoing.end(); ++this_trans_iter)
{
for (TransSet::const_iterator fa_trans_iter = fa_outgoing.begin();
fa_trans_iter != fa_outgoing.end(); ++fa_trans_iter)
{
if (*sym_iter == WALI_EPSILON
&& (*this_trans_iter)->from() == (*this_trans_iter)->to()
&& (*fa_trans_iter)->from() == (*fa_trans_iter)->to())
{
sem_elem_t tw = (*this_trans_iter)->weight(), fw = (*fa_trans_iter)->weight();
assert(tw->equal(tw->one()));
assert(fw->equal(fw->one()));
continue;
}
details::handle_transition(dest, worklist,
wmaker, zero,
*this_trans_iter, *fa_trans_iter,
*this, fa);
} // for each transition in fa_outgoing
} // for each transition in this_outgoing
delete left_no_motion;
delete right_no_motion;
}// for each alphabet
} // while (worklist)
}
//
// Intersect this and fa, storing the result in dest
// TODO: Note: if this == dest there might be a problem
//
void WFA::intersect_cross(
WeightMaker& wmaker
, WFA const & fa
, WFA& dest ) const
{
query_t lhsQuery = getQuery();
// Hash transitions of fa on stack symbol. Then probe the hash
// with this's transitions to add transitions to dest
StackHasher hashfa;
fa.for_each(hashfa);
StackHasher hashThis;
for_each( hashThis );
// Store init state
Key dest_init_state = getKey(initial_state(),fa.initial_state());
// Store final states
// Pairwise cross of the sets
std::set< Key > dest_final_states;
std::set< Key >::iterator keyit = F.begin();
std::set< Key >::iterator keyitEND = F.end();
for( ; keyit != keyitEND ; keyit++ )
{
std::set< Key >::iterator fait = fa.F.begin();
std::set< Key >::iterator faitEND = fa.F.end();
for( ; fait != faitEND ; fait++ )
{
dest_final_states.insert( getKey(*keyit,*fait) );
}
}
// Do this here in case dest == this
State const * initThis = getState(getInitialState());
State const * initFa = fa.getState(fa.getInitialState());
if( initThis == NULL || initFa == NULL )
{
*waliErr << "[ERROR - WFA::intersect] No initial state.\n";
*waliErr << "\tIntersection must be empty.\n";
return;
}
sem_elem_t stateWeight =
wmaker.make_weight( initThis->weight()->zero()
, initFa->weight()->zero() );
// Reset dest
dest.clear();
// Note: We need to make sure the state exists b/c
// setInitialState cannot call addState because there is no
// weight to call it with
dest.addState( dest_init_state, stateWeight->zero() );
// Set dest init state
dest.setInitialState( dest_init_state );
// Set dest final states
keyit = dest_final_states.begin();
keyitEND = dest_final_states.end();
for( ; keyit != keyitEND ; keyit++ )
{
Key f = *keyit;
dest.addState(f,stateWeight->zero());
dest.addFinalState(f);
}
// Set result's query mode
dest.setQuery( lhsQuery );
// Perform intersection
StackHasher::iterator stit = hashThis.begin();
StackHasher::iterator stitEND = hashThis.end();
for( ; stit != stitEND ; stit++ )
{
// Probe StackHasher outside of the inner
StackHasher::stackmap_t::iterator stkit( hashfa.stackmap.find( stit->first ) );
if( stkit == hashfa.stackmap.end() )
{
//std::cout << "\tSkipping '" << key2str(stit->first) << "'\n";
continue;
}
// for each trans in (TransSet) stit->second
StackHasher::ConstTransSet& tsThis = stit->second;
StackHasher::ConstTransSet::iterator tsit = tsThis.begin();
StackHasher::ConstTransSet::iterator tsitEND = tsThis.end();
for( ; tsit != tsitEND ; tsit++ )
{
ITrans const * t = *tsit;
// for each trans in (TransSet) stkit->second
StackHasher::ConstTransSet::iterator stklsit = stkit->second.begin();
StackHasher::ConstTransSet::iterator stklsitEND = stkit->second.end();
for( ; stklsit != stklsitEND ; stklsit++ )
{
ITrans const * t2 = *stklsit;
Key fromkey = getKey( t->from(),t2->from() );
Key tokey = getKey( t->to(),t2->to() );
sem_elem_t W = wmaker.make_weight(t ,t2);
ITrans* newTrans = new Trans(fromkey,t->stack(),tokey,W);
//std::cout << "--- Because:\n";
//t->print(std::cout << "--- right (this) contains ") << std::endl;
//t2->print(std::cout << "--- left (other) contains ") << std::endl;
//newTrans->print( std::cout << "--- Adding Trans: " ) << std::endl;
dest.addTrans( newTrans );
}
}
}
}
//
// Simply delegates to the Tarjan algorithm
//
regex::regex_t WFA::toRegex() {
return TarjanBasicRegex();
}
//
// Removes all transitions <b>not</b> in the (init_state,F) chop
//
void WFA::prune()
{
// First, remove all transitions with zero weight
TransZeroWeight tzw;
for_each(tzw);
TransSet::iterator transit = tzw.zeroWeightTrans.begin();
for(; transit != tzw.zeroWeightTrans.end(); transit++) {
ITrans *t = *transit;
erase(t->from(), t->stack(), t->to());
}
tzw.zeroWeightTrans.clear();
// Now, do the (init_state, F) chop
DefaultWorklist<State> wl;
PredHash_t preds;
setupFixpoint( wl,NULL,&preds );
FOR_EACH_STATE(resetState) {
resetState->tag = 0;
}
FOR_EACH_FINAL_STATE(finalState) {
finalState->tag = 1;
}
// first backwards prune
while( !wl.empty() )
{
State* q = wl.get();
PredHash_t::iterator predHashIt = preds.find(q->name());
if( predHashIt == preds.end() ) {
continue;
}
StateSet_t& stateSet = predHashIt->second;
StateSet_t::iterator stateIt = stateSet.begin();
StateSet_t::iterator stateItEND = stateSet.end();
//sem_elem_t ONE = q->weight()->one();
//sem_elem_t ZERO = q->weight()->zero();
for( ; stateIt != stateItEND ; stateIt++ )
{
State* p = *stateIt;
if( p->tag == 0 ) {
p->tag = 1;
wl.put(p);
}
}
}
State* init = getState( getInitialState() );
{ // BEGIN DEBUGGING
assert( init != 0 );
} // END DEBUGGING
// go from 1->2 or 0->1
init->tag++;
wl.put(init);
while( ! wl.empty() ) {
State* p = wl.get();
TransSet& tSet = p->getTransSet();
TransSet::iterator it = tSet.begin();
TransSet::iterator itEND = tSet.end();
TransSet::iterator eraseIt;
// for each (p,_,q)
// mark q reached
while( it != itEND ) {
ITrans* t = *it;
eraseIt = it;
it++;
State* q = getState(t->to());
// A state that was backwards reachable from a final state
// will have a tag of 1. Set tag to 2 to signify it is
// also forwards reachable
if( q->tag == 1 ) {
q->tag = 2;
wl.put(q);
}
else if( q->tag == 0 ) {
// A tag of 0 means the State is not backwards
// reachable. However, since State p was on the
// worklist it is forwards reachable and will not be
// removed. Therefore, we must manually remove these
// transitions.
//
// Simple example:
// (p,a) -> acc
// (p,b) -> bad
//
// If we do not remove (p,b) -> bad here, it will be
// leftover
eraseTransFromKpMap(t);
eraseTransFromEpsMap(t);
tSet.erase(eraseIt);
delete t;
}
}
}
//
// States that have a tag of 2 are forwards and backwards
// reachable. Erase all other states.
//
std::vector<State*> to_erase;
FOR_EACH_STATE( eraseMe ) {
if( eraseMe->tag != 2 ) {
{ // BEGIN DEBUGGING
//*waliErr << "Erasing State '" << key2str(eraseMe->name()) << "'\n";
} // END DEBUGGING
to_erase.push_back(eraseMe);
}
}
for (std::vector<State*>::const_iterator eraseMe = to_erase.begin();
eraseMe != to_erase.end(); ++eraseMe)
{
eraseState(*eraseMe);
}
}
//
// Intersect (in place) with (stk \Gamma^*)
//
void WFA::filter(Key stk) {
std::set<Key> stkset;
stkset.insert(stk);
filter(stkset);
}
//
// Intersect (in place) with (stk \Gamma^*)
//
void WFA::filter(std::set<Key> &stkset) {
if(kpmap.size() == 0) return;
// Remove outgoing transitions from the init state that do not
// have stack in stkset
State *init = getState(getInitialState());
assert(init != 0);
State::iterator tit = init->begin();
State::iterator titEND = init->end();
// List of transitions to be deleted
std::list<ITrans *> to_delete;
for( ; tit != titEND ; tit++ ) {
ITrans* t = *tit;
if(stkset.find(t->stack()) == stkset.end()) {
to_delete.push_back(t);
}
}
std::list<ITrans *>::iterator lit;
for(lit = to_delete.begin(); lit != to_delete.end(); lit++) {
ITrans* t = *lit;
erase(t->from(), t->stack(), t->to());
}
// prune
prune();
}
//
// @brief print WFA to param o
//
std::ostream & WFA::print( std::ostream & o ) const
{
o << "WFA -\n";
o << " Initial State : ";
o << key2str(init_state) << std::endl;
// Q
o << " Q: {";
std::set< Key >::const_iterator cit = Q.begin();
std::set< Key >::const_iterator citEND = Q.end();
for( bool first=true; cit != citEND ; cit++,first=false )
{
if(!first)
o << ", ";
o << key2str( *cit );
}
o << "}\n";
// F
o << " F: {";
cit = F.begin();
citEND = F.end();
for( bool first=true; cit != citEND ; cit++,first=false )
{
if(!first)
o << ", ";
o << key2str( *cit );
}
o << "}\n";
TransPrinter printer( o );
for_each( printer );
o << "\nWeights on states: \n";
state_map_t::const_iterator sit = state_map.begin();
state_map_t::const_iterator sitEND = state_map.end();
for(; sit != sitEND; sit++)
{
o << key2str( sit->first ) << " " << sit->second << ": \n";
sit->second->weight()->print( o << "\tWeight: " ) << "\n";
sit->second->acceptWeight()->print(o << "\tAccept: ") << "\n";
}
return o;
}
//
// @brief Print WFA in dot format
//
std::ostream& WFA::print_dot(
std::ostream& o,
bool print_weights,
DotAttributePrinter * attribute_printer ) const
{
o << "digraph \"WFA@" << std::hex << (void*)this << std::dec << "\" {\n";
TransDotty dotter( o, print_weights, attribute_printer );
for_each(dotter);
state_map_t::const_iterator stit = state_map.begin();
state_map_t::const_iterator stitEND = state_map.end();
for( ; stit != stitEND ; stit++ )
{
Key key = stit->first;
o << "\t" << key << " [label=\"";
o << key2str(key);
o << "\"";
if( isInitialState(key) ) {
o << ",color=green,style=filled";
}
else if( isFinalState(key) ) {
o << ",color=lightblue,style=filled";
}
if (attribute_printer) {
attribute_printer->print_extra_attributes(stit->second, o);
}
o << "];\n";
}
o << "}\n";
return o;
}
//
// @brief marshall WFA in XML
//
std::ostream& WFA::marshall( std::ostream& o ) const
{
o << "<" << XMLTag;
switch( query ) {
case REVERSE:
o << " " << XMLQueryTag << "='REVERSE'>\n";
break;
case INORDER:
case MAX:
o << " " << XMLQueryTag << "='INORDER'>\n";
break;
}
// do initial state
marshallState(o,init_state);
// do final states
std::set< Key >::const_iterator Fit = F.begin();
std::set< Key >::const_iterator FitEND = F.end();
for( ; Fit != FitEND ; Fit++ )
{
marshallState(o,*Fit);
}
TransMarshaller marsh(o);
for_each(marsh);
o << "</" << XMLTag << ">\n";
return o;
}
std::ostream& WFA::marshallState( std::ostream& o,Key key ) const
{
// <State
o << "\t<" << State::XMLTag;
// _Name='<name>'
o << " " << State::XMLNameTag << "='" << key2str( key ) << "'";
if( isInitialState(key) ) {
// _initial='TRUE'
o << " " << State::XMLInitialTag << "='TRUE'";
}
if( isFinalState(key) ) {
// if is final, then _final='TRUE'
o << " " << State::XMLFinalTag << "='TRUE'";
}
getState(key)->weight()->marshallWeight(o << ">");
o << "</" << State::XMLTag << ">\n";
return o;
}
//
// Inserts tnew into the WFA. If a transition matching tnew
// exists, tnew is deleted.
//
std::pair<ITrans *, bool>
WFA::insert( ITrans* tnew )
{
bool inserted = true;
////
// WFA::find code duplicated to keep
// a handle on the kp_map_t::iterator
////
ITrans* told = 0;
kp_map_t::iterator it = kpmap.find(tnew->keypair());
if( it != kpmap.end() )
{
TransSet& transSet = it->second;
TransSet::iterator tsit= transSet.find(tnew);
if( tsit != transSet.end() ) {
told = *tsit;
}
}
////
// Cases
// if 0 == told (told does not exist)
// if it == kpmap.end
// (p,g,*) does not exist
// else
// just add (p,g,q) to it.second
// else (0 != told)
// combine new val w/ old
//
////
if( 0 == told )
{
sem_elem_t ZERO( tnew->weight()->zero() );
//*waliErr << "\tAdding 'from' state'" << key2str(t->from()) << "'\n";
addState( tnew->from(), ZERO );
//*waliErr << "\tAdding 'to' state '" << key2str(t->to()) << "'\n";
addState( tnew->to(), ZERO );
if( it == kpmap.end() )
{
TransSet transSet;
it = kpmap.insert(tnew->keypair(),transSet).first;
}
it->second.insert(tnew);
// Set told to tnew for the return statement at end of
// method
told = tnew;
// Add tnew to the 'to' State's reverse trans list
state_map_t::iterator from_stit = state_map.find( tnew->from() );
{ // BEGIN DEBUGGING
if( from_stit == state_map.end() ) {
tnew->print( *waliErr << "\n\n+++ WTF +++\n" ) << std::endl;
assert( Q.find(tnew->from()) != Q.end() );
assert( from_stit != state_map.end() );
}
} // END DEBUGGING
from_stit->second->addTrans( tnew );
// if tnew is an eps transition add to eps_map
if( tnew->stack() == WALI_EPSILON )
{
eps_map_t::iterator epsit = eps_map.find( tnew->to() );
if( epsit == eps_map.end() ) {
TransSet transSet;
epsit = eps_map.insert( tnew->to(),transSet ).first;
}
epsit->second.insert( tnew );
}
}
else {
// Safety check. If told == tnew then the combine
// is a waste of effort and the deletion is just plain
// wrong.
if( told != tnew ) {
// combine new into old
told->combineTrans( tnew );
delete tnew;
inserted = false;
}
else {
*waliErr << "[WARNING - WFA::insert]\n";
*waliErr << "\tAttempt to insert 'Trans' already owned by WFA.\n";
}
}
return std::make_pair(told, inserted);
}
TransSet WFA::match( Key p, Key y ) const {
KeyPair kp(p,y);
kp_map_t::const_iterator it = kpmap.find(kp);
return (it != kpmap.end()) ? it->second : TransSet();
}
//
// Add a state to the state map
//
void WFA::addState( Key key , sem_elem_t zero )
{
if( state_map.find( key ) == state_map.end() ) {
State* state = new State(key,zero);
state_map.insert( key , state );
Q.insert(key);
}
}
const State* WFA::getState( Key name ) const
{
state_map_t::const_iterator stit = state_map.find( name );
if( stit == state_map.end() ) {
return NULL;
}
else {
const State * state = stit->second;
return state;
}
}
const std::set< Key >& WFA::getStates() const
{
return Q;
}
const std::set< Key >& WFA::getFinalStates() const
{
return F;
}
///////////////////////
// Begin protected WFA
///////////////////////
//
// Return State * corresponding to the key
//
State * WFA::getState( Key name )
{
state_map_t::iterator stit = state_map.find( name );
if( stit == state_map.end() ) {
//throw NoSuchStateException( name );
return NULL;
}
else {
State * state = stit->second;
//return *state;
return state;
}
}
//
// Place WFA in state ready for fixpoint
// Initialize weight on final states to be st (if it is NULL, then ONE)
//
void WFA::setupFixpoint( Worklist<State>& wl, IncomingTransMap_t* trans, PredHash_t* preds) {
sem_elem_t nullwt; // treated as ONE
setupFixpoint(wl, trans, preds, nullwt);
}
//
// Place WFA in state ready for fixpoint
// Initialize weight on final states to be st (if it is NULL, then ONE)
//
void WFA::setupFixpoint( Worklist<State>& wl, IncomingTransMap_t* trans, PredHash_t* preds, sem_elem_t wtFinal )
{
state_map_t::iterator it = state_map.begin();
state_map_t::iterator itEND = state_map.end();
bool first = true;
sem_elem_t ZERO,ONE;
for( ; it != itEND ; it++ )
{
// State p
State* st = it->second;
// Get a handle on ONE and ZERO.
// Do it here b/c we do not have a way to
// get the ONE and ZERO weights w/out first
// having a weight, i.e. st->weight()
// Further if wtFinal was provided, use that.
if(first){
if(wtFinal!=NULL){
ONE = wtFinal->one();
ZERO = wtFinal->zero();
}else{
ONE = st->weight()->one();
ZERO = st->weight()->zero();
wtFinal = ONE;
}
first = false;
}
st->unmark();
if( isFinalState( st->name() ) ) {
st->weight() = wtFinal;
st->delta() = wtFinal;
wl.put( st );
}
else {
st->weight() = ZERO;
st->delta() = ZERO;
}
State::iterator stit = st->begin();
State::iterator stEnd = st->end();
for( ; stit != stEnd; stit++ ) {
// (p,_,q)
ITrans* t = *stit;
Key toKey = t->to();
if (preds != NULL) {
PredHash_t::iterator predIt = preds->find(toKey);
if( predIt == preds->end() ) {
StateSet_t stateSet;
predIt = preds->insert(toKey,stateSet).first;
}
//*waliErr << "Adding '" << key2str(st->name()) << "' to pred of '";
//*waliErr << key2str(toKey) << "'\n";
predIt->second.insert( st );
}
if (trans != NULL) {
IncomingTransMap_t::iterator transIt = trans->find(toKey);
if( transIt == trans->end() ) {
std::vector<ITrans*> transitions;
transIt = trans->insert(toKey, transitions).first;
}
//*waliErr << "Adding transition from '" << key2str(st->name()) << "' to pred of '";
//*waliErr << key2str(toKey) << "'\n";
transIt->second.push_back(t);
}
}
}
}
//
// Removes Trans(from,stack,to) from the kpmap. Returns true
// if the Trans was erased, i.e., the Trans existed.
//
ITrans* WFA::eraseTransFromKpMap(
Key from,
Key stack,
Key to )
{
// ignore weight on Trans
Trans terase(from,stack,to,0);
return eraseTransFromKpMap(&terase);
}
ITrans* WFA::eraseTransFromKpMap( ITrans* terase )
{
ITrans* tret = NULL;
kp_map_t::iterator kpit = kpmap.find( terase->keypair() );
// remove from kpmap
if( kpit != kpmap.end() ) {
tret = kpit->second.erase(terase);
}
return tret;
}
ITrans* WFA::eraseTransFromEpsMap( ITrans* terase )
{
ITrans* tret = NULL;
if( terase->stack() == WALI_EPSILON )
{
// remove from epsmap
// This loop could be moved to its own method
eps_map_t::iterator epit = eps_map.find( terase->to() );
if( epit != eps_map.end() ) {
tret = epit->second.erase(terase);
}
}
return tret;
}
bool
WFA::eraseState(State* state)
{
// Remove incoming and outgoing transitions
details::TransRemover remover(state->name());
this->for_each(remover);
remover.removeFrom(this);
// Remove the state itself
Q.erase(state->name());
F.erase(state->name());
state_map.erase(state->name());
// This is because of dumb bookkeeping stuff. I can't actually
// delete the state at this point because of some reason, but we
// make a note of the fact that we've deleted it so we can
// remove it when the WFA is destroyed.
deleted_states.insert(state);
return true;
}
/*!
* TODO - future uses
* One can imagine that a regular expression
* for states other than the initial state is
* desirable. To do so, either this method
* should take the desired key or it should
* return the resultant vector.
*
* @see Tarjan's paper on path expressions
*/
wali::regex::regex_t WFA::TarjanBasicRegex()
{
using namespace wali::regex;
typedef wali::HashMap<wali::Key,int> index_map_t;
std::vector<wali::Key> order(Q.size());
std::vector<regex_t> nodes(Q.size()); // holds answer
index_map_t index_map;
{
std::set<wali::Key>::iterator it = Q.begin();
for( int i=0; it != Q.end() ; i++, it++ ) {
order[i] = *it;
index_map.insert(*it,i);
}
}
const size_t n = order.size();
regex_t **P = new regex_t*[n];
// initialize
for( size_t i=0 ; i < n ; i++ ) {
P[i] = new regex_t[n];
for( size_t j=0 ; j < n ; j++ ) {
P[i][j] = Regex::NIL();
}
}
// for e \in E, P(h(e),t(e)) := [P(h(e),t(e)) \cup e]
for( size_t i=0; i < n ; i++ ) {
wali::Key hd = order[i];
State* state = getState(hd);
TransSet::iterator it = state->begin();
for( ; it != state->end() ; it++ ) {
ITrans* t = *it;
index_map_t::iterator lkup = index_map.find(t->to());
assert( lkup != index_map.end() );
const int tl = lkup->second;
{ // DEBUGGING
//P[i][tl]->print( *eout << "\tOLD(" << i << "," << tl << ") : " ) << std::endl;
}
P[i][tl] = Regex::COMBINE(P[i][tl],Root::make(t->stack(),t->weight()));
{ // DEBUGGING
//P[i][tl]->print( *eout << "\tP(" << i << "," << tl << ") : " ) << std::endl;
}
}
}
// loop for v = 1 until n do
// construct the path sequence
for( size_t v = 0; v < n ; v++ ) {
P[v][v] = Regex::STAR(P[v][v]);
for( size_t u = v+1; u < n ; u++ ) {
// 0 \extend 0 == 0
if( P[u][v]->isZero() ) continue;
//P[u][v] = Regex::EXTEND(P[u][v],P[v][v]);
P[u][v] = this->EXTEND(P[u][v],P[v][v]);
for( size_t w = v+1; w < n ; w++ ) {
// 0 \extend 0 == 0
if( P[v][w]->isZero() ) continue;
//P[u][w] = Regex::COMBINE(P[u][w],Regex::EXTEND(P[u][v],P[v][w]));
P[u][w] = Regex::COMBINE(P[u][w],this->EXTEND(P[u][v],P[v][w]));
{ // DEBUGGING
//P[u][w]->print( *eout << "\tP(" << u << "," << w << ") : " ) << std::endl;
}
}
}
}
index_map_t::iterator lkup = index_map.find(getInitialState());
// If there are no transitions starting from the initial state,
// return Regex::NIL().
//assert(lkup != index_map.end());
if (lkup == index_map.end())
{
*waliErr << "[WARNING] No transitions from initial state." << std::endl;
for( size_t i=0; i < n ; i++ ) {
{ // DEBUGGING
//nodes[i]->print( *eout << "(" << i << ") " ) << std::endl;
}
delete[] P[i];
}
delete[] P;
return Regex::NIL();
}
const int init_idx = lkup->second;
for( size_t i=0; i < n; i++) {
nodes[i] = Regex::NIL();
}
nodes[init_idx] = Regex::ID();
for( size_t u=0; u < n ; u++) {
for( size_t w =u; w < n ; w++) {
if( w == u && P[u][u]->isOne() ) continue;
if( P[u][w]->isZero() ) continue;
if( u == w ) {
//nodes[u] = Regex::EXTEND(nodes[u],P[u][w]);
nodes[u] = this->EXTEND(nodes[u],P[u][w]);
}
else {
//nodes[w] = Regex::COMBINE(nodes[w], Regex::EXTEND(nodes[u],P[u][w]));
nodes[w] = Regex::COMBINE(nodes[w], this->EXTEND(nodes[u],P[u][w]));
}
}
}
for( long u = static_cast<long>(n)-1; u >= 0; u-- ) {
for( long w = u-1; w >=0 ; w-- ) {
if( P[u][w]->isZero() ) continue;
if( u == w ) {
//nodes[u] = Regex::EXTEND(nodes[u],P[u][w]);
nodes[u] = this->EXTEND(nodes[u],P[u][w]);
}
else {
//nodes[w] = Regex::COMBINE(nodes[w],Regex::EXTEND(nodes[u],P[u][w]));
nodes[w] = Regex::COMBINE(nodes[w],this->EXTEND(nodes[u],P[u][w]));
}
}
}
// now return nodes[INDEX(getInitialState())]
std::set< wali::Key >::iterator fit = F.begin();
regex_t answer = Regex::NIL();
for( ; fit != F.end() ; fit++ ) {
wali::Key f = *fit;
index_map_t::iterator mit = index_map.find(f);
if( mit != index_map.end() ) {
answer = Regex::COMBINE(answer,nodes[mit->second]);
}
}
for( size_t i=0; i < n ; i++ ) {
{ // DEBUGGING
//nodes[i]->print( *eout << "(" << i << ") " ) << std::endl;
}
delete[] P[i];
}
delete[] P;
return answer;
}
regex::regex_t WFA::EXTEND(regex::regex_t a , regex::regex_t b) {
return (query == INORDER) ?
regex::Regex::EXTEND(a,b) : regex::Regex::EXTEND(b,a);
}
//////////////
// Helper functions
/// Adds to 'accessible' the fact that it is possible to reach the
/// destination of the transition 'trans' with the weight of 'trans'. If
/// that state was already known to be reachable, joins the new weight
/// with the old one.
bool add_trans_to_accessible_states(WFA::AccessibleStateMap & accessible,
Key dest, sem_elem_t weight)
{
assert(weight.get_ptr());
if (accessible.find(dest) != accessible.end()) {
sem_elem_t old = accessible[dest];
weight = weight->combine(old);
if (weight->equal(old.get_ptr())) {
// No change
return false;
}
}
// Either this is a new accessible state or the weight changed
accessible[dest] = weight;
return true;
}
/// Like dest += src. For any key in src not in dest, add it with the
/// weight in src. For keys in both, dest's weight is set to the combine.
void merge_state_maps(WFA::AccessibleStateMap & dest,
WFA::AccessibleStateMap const & src)
{
for (WFA::AccessibleStateMap::const_iterator state = src.begin();
state != src.end(); ++state)
{
add_trans_to_accessible_states(dest, state->first, state->second);
}
}
WFA::AccessibleStateMap
WFA::simulate(AccessibleStateMap const & start,
Word const & word) const
{
AccessibleStateMap before = start;
AccessibleStateMap after;
EpsilonCloseCache eclose_cache;
for (AccessibleStateMap::const_iterator start_it = start.begin();
start_it != start.end(); ++start_it)
{
AccessibleStateMap eclose = epsilonCloseCached(start_it->first, eclose_cache);
merge_state_maps(before, eclose);
}
for (Word::const_iterator pos = word.begin(); pos != word.end(); ++pos) {
// Figure out where the machine will be in the next step from each of
// the current positions.
after.clear();
Key letter = *pos;
for (AccessibleStateMap::const_iterator start_config = before.begin();
start_config != before.end(); ++start_config)
{
Key source = start_config->first;
sem_elem_t source_weight = start_config->second;
// Where can we go from this position?
if (kpmap.find(KeyPair(source, letter)) != kpmap.end()) {
TransSet const & transitions = kpmap.find(KeyPair(source, letter))->second;
for (TransSet::const_iterator trans_it = transitions.begin();
trans_it != transitions.end(); ++trans_it)
{
AccessibleStateMap eclose = epsilonCloseCached((*trans_it)->to(), eclose_cache);
for (AccessibleStateMap::const_iterator dest = eclose.begin();
dest != eclose.end(); ++dest)
{
// We have
// (start) - - - - - > (source) ---> (trans_it->->to()) - - - - - > (dest->first)
// source_weight trans_it->->weight() dest->second
assert(dest->second.get_ptr());
sem_elem_t weight = source_weight->extend((*trans_it)->weight()->extend(dest->second));
add_trans_to_accessible_states(after, dest->first, weight);
}
} // For each outgoing transition
} // if there are outgoing transitions...
} // For each possible starting configuration
// Now after holds the list of starting positions. After this, before
// will.
swap(after, before);
} // For each letter in 'word'
return before;
}
bool
WFA::isAcceptedWithNonzeroWeight(Word const & word) const
{
AccessibleStateMap start;
start[getInitialState()] = this->getSomeWeight()->one();
AccessibleStateMap finish = simulate(start, word);
std::set<Key> const & finals = getFinalStates();
for(std::set<Key>::const_iterator final = finals.begin();
final != finals.end(); ++final)
{
if (finish.find(*final) != finish.end()) {
sem_elem_t weight = finish[*final];
if (!weight->equal(weight->zero())) {
return true;
}
}
}
return false;
}
typedef std::set<Key> KeySet;
static
bool
any_final(WFA const & wfa, KeySet const & states)
{
for(KeySet::const_iterator state = states.begin();
state != states.end(); ++state)
{
if (wfa.isFinalState(*state)) {
return true;
}
}
return false;
}
std::map<Key, std::map<Key, KeySet> >
WFA::next_states_no_eclose(WFA const & wfa, KeySet const & froms)
{
// symbol -> source -> keyset
std::map<Key, std::map<Key, KeySet> > nexts;
for(KeySet::const_iterator from = froms.begin();
from != froms.end(); ++from)
{
// For each outgoing non-epsilon transition from 'from'...
for (kp_map_t::const_iterator kpmap_iter = wfa.kpmap.begin();
kpmap_iter != wfa.kpmap.end(); ++kpmap_iter)
{
Key source = kpmap_iter->first.first;
Key symbol = kpmap_iter->first.second;
if (source == *from
&& symbol != WALI_EPSILON)
{
TransSet const & outgoing = kpmap_iter->second;
for (TransSet::const_iterator trans = outgoing.begin();
trans != outgoing.end(); ++trans)
{
// ...for each
nexts[symbol][source].insert( (*trans)->to() );
} // for "each" outgoing transition [part 1]
} // for "each" outgoing transition [part 2]
} // for "each" outgoing transition [part 3]
} // for each nondeterministic possibility
return nexts;
}
WFA
WFA::semideterminize(DeterminizeWeightGen const & wg) const
{
std::stack<KeySet> worklist;
std::set<Key> visited;
EpsilonCloseCache eclose_cache;
WFA result;
sem_elem_t one = wg.getOne(*this);
sem_elem_t zero = one->zero();
{
// Set up initial states
KeySet det_initial;
AccessibleStateMap initials = epsilonCloseCached(this->getInitialState(), eclose_cache);
for (AccessibleStateMap::const_iterator initial = initials.begin();
initial != initials.end(); ++initial)
{
det_initial.insert(initial->first);
}
Key initial_key = getKey(det_initial);
result.addState(initial_key, zero);
result.setInitialState(initial_key);
worklist.push(det_initial);
visited.insert(initial_key);
}
while (!worklist.empty())
{
KeySet sources = worklist.top();
worklist.pop();
Key sources_key = getKey(sources);
result.addState(sources_key, zero);
if (any_final(*this, sources)) {
sem_elem_t accept_weight = wg.getAcceptWeight(*this, result, sources);
result.addFinalState(sources_key, accept_weight);
}
// symbol -> source -> next states [no eclose]
std::map<Key, std::map<Key, KeySet> > nexts
= next_states_no_eclose(*this, sources);
for (std::map<Key, std::map<Key, KeySet> >::const_iterator next_by_source = nexts.begin();
next_by_source != nexts.end(); ++next_by_source)
{
Key symbol = next_by_source->first;
KeySet targets;
// weight_spec[p][q] will represent the weight of
//
// symbol epsilon
// p -------> i - - - - - -> q
//
// Each 'p' that is possible is a key in next->second. Each 'i'
// that is possible is a an element of next->second[p].
std::map<Key, AccessibleStateMap> weight_spec;
// source -> next states [no eclose]
for (std::map<Key, KeySet>::const_iterator next = next_by_source->second.begin();
next != next_by_source->second.end(); ++next)
{
Key source = next->first;
KeySet const & intermediates = next->second;
for (KeySet::const_iterator i = intermediates.begin();
i != intermediates.end(); ++i)
{
Trans trans_p_to_i;
bool found = this->find(source, symbol, *i, trans_p_to_i);
assert(found);
AccessibleStateMap eclose = epsilonCloseCached(*i, eclose_cache);
for (AccessibleStateMap::const_iterator q_w = eclose.begin();
q_w != eclose.end(); ++q_w)
{
weight_spec[source][q_w->first] = trans_p_to_i.weight()->extend(q_w->second);
targets.insert(q_w->first);
}
}
}
// Only add a transition if it doesn't go to {}. Why? This is borne
// out of the difference between determinize and
// semideterminize. Determinize "can't" produce a total
// automaton. However, without this check, it still inserts the
// initial transitions to {}. From the point of view of producing
// an incomplete automaton, these transitions are dumb. So we get
// rid of them.
if (targets.size() > 0) {
Key target_key = getKey(targets);
sem_elem_t weight = wg.getWeight(*this, result, weight_spec, sources, symbol, targets);
result.addTrans(sources_key, symbol, target_key, weight);
std::pair<KeySet::iterator, bool> p = visited.insert(target_key);
if (p.second) {
// It wasn't already there
worklist.push(targets);
}
}
}
}
return result;
}
WFA
WFA::semideterminize() const
{
AlwaysReturnOneWeightGen wg(getSomeWeight());
return semideterminize(wg);
}
WFA
WFA::determinize(DeterminizeWeightGen const & wg) const
{
WFA det = semideterminize(wg);
det.complete();
return det;
}
WFA
WFA::determinize() const
{
AlwaysReturnOneWeightGen wg(getSomeWeight());
return determinize(wg);
}
static
size_t
fact(size_t n) {
if (n == 1) {
return 1;
}
else {
return n * fact(n-1);
}
}
template<typename MapType>
typename MapType::mapped_type
get(MapType const & m, typename MapType::key_type key)
{
typename MapType::const_iterator place = m.find(key);
if (place == m.end()) {
// TODO: this should throw something, conditional on
// exceptions being enabled.
assert(false);
return typename MapType::mapped_type();
}
return place->second;
}
static
bool
transitions_match(TransSet const & left_trans_set,
TransSet const & right_trans_set,
std::map<Key, Key> const & left_to_right,
bool check_weights)
{
for (TransSet::const_iterator trans_it = left_trans_set.begin();
trans_it != left_trans_set.end(); ++trans_it)
{
ITrans const * left_trans = *trans_it;
Key right_from_needed = get(left_to_right, left_trans->from());
Key right_to_needed = get(left_to_right, left_trans->to());
TransSet::const_iterator r_place = right_trans_set.find(right_from_needed,
left_trans->stack(),
right_to_needed);
if (r_place == right_trans_set.end()) {
// There was no such transition
return false;
}
ITrans const * right_trans = *r_place;
if (!left_trans->weight()->equal(right_trans->weight().get_ptr())
&& check_weights)
{
return false;
}
}
return true;
}
bool
WFA::is_isomorphism(WFA const & left, std::vector<Key> const & left_states,
WFA const & right, std::vector<Key> const & right_states,
bool check_weights)
{
assert(left_states.size() == right_states.size());
std::map<Key, Key> left_to_right;
for (size_t state_index = 0; state_index < left_states.size(); ++state_index) {
left_to_right[left_states[state_index]]
= right_states[state_index];
}
for (size_t state_index = 0; state_index < left_states.size(); ++state_index) {
Key left_state = left_states[state_index];
Key right_state = right_states[state_index];
if ((!left.getState(left_state)->weight()->equal(
right.getState(right_state)->weight().get_ptr())
|| !left.getState(left_state)->acceptWeight()->equal(
right.getState(right_state)->acceptWeight().get_ptr()))
&& check_weights)
{
return false;
}
if (left.isInitialState(left_state) != right.isInitialState(right_state)) {
// One is the start state and the other isn't
return false;
}
if (left.isFinalState(left_state) != right.isFinalState(right_state)) {
// One accepts and the other rejects
return false;
}
for (kp_map_t::const_iterator kpmap_iter = left.kpmap.begin();
kpmap_iter != left.kpmap.end(); ++kpmap_iter)
{
Key left_source = kpmap_iter->first.first;
if (left_source == left_state) {
// We're looking at outgoing transitions from left_state
Key right_source = left_to_right[left_source];
Key symbol = kpmap_iter->first.second;
kp_map_t::const_iterator r_place = right.kpmap.find(KeyPair(right_source, symbol));
if (r_place == right.kpmap.end()) {
// There is no outgoing transition on (source, symbol)
return false;
}
TransSet const & left_trans_set = kpmap_iter->second;
TransSet const & right_trans_set = r_place->second;
if (!transitions_match(left_trans_set, right_trans_set,
left_to_right, check_weights))
{
return false;
}
// All transitions from left/right under symbol match
}
}
// Everything about left/right states themselves and outgoing
// transitions match. Time to check the next pair.
}
return true;
}
bool
WFA::isIsomorphicTo(WFA const & other) const
{
return isIsomorphicTo(other, true);
}
bool
WFA::isIsomorphicTo(WFA const & other, bool check_weights) const
{
std::vector<Key> left_states(getStates().begin(),
getStates().end());
std::vector<Key> right_states(other.getStates().begin(),
other.getStates().end());
if (left_states.size() != right_states.size()) {
return false;
}
size_t count = 0; // Sanity checking
do {
if (is_isomorphism(*this, left_states, other, right_states, check_weights)) {
return true;
}
++count;
} while(std::next_permutation(right_states.begin(), right_states.end()));
assert(count == fact(getStates().size()));
return false;
}
bool
WFA::equal(WFA const & that) const
{
if (this->Q.size() != that.Q.size()
|| this->F.size() != that.F.size()
|| this->getInitialState() != that.getInitialState())
{
return false;
}
for (std::set<Key>::const_iterator this_final = this->F.begin();
this_final != this->F.end(); ++this_final)
{
if (!that.isFinalState(*this_final)) {
return false;
}
}
// Initial and final states are all the same. Check other states.
for (state_map_t::const_iterator this_state_iter = this->state_map.begin();
this_state_iter != this->state_map.end(); ++this_state_iter)
{
State const
* this_state = this_state_iter->second,
* that_state = that.getState(this_state_iter->first);
if (that_state == NULL // state isn't present
|| ! this_state->weight()->equal(that_state->weight())
|| ! this_state->acceptWeight()->equal(that_state->acceptWeight())
|| this_state->getTransSet().size() != that_state->getTransSet().size())
{
return false;
}
}
// All states and state weights are the same. Check transitions.
for (kp_map_t::const_iterator this_transset_iter = this->kpmap.begin();
this_transset_iter != this->kpmap.end(); ++this_transset_iter)
{
if(this_transset_iter->second.size() == 0u) {
continue;
}
kp_map_t::const_iterator that_transset_iter = that.kpmap.find(this_transset_iter->first);
if (that_transset_iter == that.kpmap.end()
|| this_transset_iter->second.size() != that_transset_iter->second.size())
{
return false;
}
for (TransSet::const_iterator this_trans_iter = this_transset_iter->second.begin();
this_trans_iter != this_transset_iter->second.end(); ++this_trans_iter)
{
// We don't have an easy way of checking presence. Do it a sucky
// way.
bool found = false;
for (TransSet::const_iterator that_trans_iter = that_transset_iter->second.begin();
that_trans_iter != that_transset_iter->second.end(); ++that_trans_iter)
{
if ((*this_trans_iter)->equalIgnoringWeight(*that_trans_iter)
&& (*this_trans_iter)->weight()->equal((*that_trans_iter)->weight()))
{
found = true;
break;
}
}
if (!found) {
return false;
}
} // for each transition in the current transset
} // for each transset
// All states and transitions are the same!
return true;
}
void WFA::complete(std::set<Key> const & symbols, Key sink_state)
{
sem_elem_t one = getSomeWeight()->one();
// We only add {} on-demand. If it's not reachable, then we don't want
// it there.
bool need_sink_state = false;
// Maps source state to set of outgoing letters. (We don't care where
// they go, just whether there is any.)
std::map<Key, KeySet> outgoing;
for (kp_map_t::const_iterator kpmap_iter = kpmap.begin();
kpmap_iter != kpmap.end(); ++kpmap_iter)
{
if (kpmap_iter->second.size() > 0) {
outgoing[kpmap_iter->first.first].insert(kpmap_iter->first.second);
}
}
KeySet states = getStates();
for (KeySet::const_iterator state = states.begin();
state != states.end(); ++state)
{
for (KeySet::const_iterator symbol = symbols.begin();
symbol != symbols.end(); ++symbol)
{
if (outgoing[*state].find(*symbol) == outgoing[*state].end()) {
need_sink_state = true;
addState(sink_state, one->zero());
addTrans(*state, *symbol, sink_state, one);
}
}
}
if (need_sink_state && states.count(sink_state) == 0u)
{
// If we don't need it, then we don't need to add transitions to and
// from it. :-) If sink_state is in 'states', then this was already
// handled by the loop above.
for (kp_map_t::const_iterator kp_iter = kpmap.begin();
kp_iter != kpmap.end(); ++kp_iter)
{
addTrans(sink_state, kp_iter->first.second, sink_state, one);
}
}
}
void WFA::complete(std::set<Key> const & symbols)
{
std::set<Key> empty;
complete(symbols, getKey(empty));
}
void WFA::complete(Key sink_state)
{
std::set<Key> symbols;
for (kp_map_t::const_iterator kpmap_iter = kpmap.begin();
kpmap_iter != kpmap.end(); ++kpmap_iter)
{
symbols.insert(kpmap_iter->first.second);
}
complete(symbols, sink_state);
}
void WFA::complete()
{
std::set<Key> empty;
complete(getKey(empty));
}
void WFA::complementStates()
{
std::set<Key> notF;
// notF = Q - F
std::set_difference(this->Q.begin(), this->Q.end(),
this->F.begin(), this->F.end(),
std::inserter(notF, notF.end()));
std::swap(this->F, notF);
}
WFA WFA::removeEpsilons() const
{
WFA result(*this);
// Step 1:
// Add new transitions around epsilon-accessible states
for (std::set<Key>::const_iterator q = Q.begin(); q != Q.end(); ++q) {
AccessibleStateMap eclose = epsilonClose(*q);
for (AccessibleStateMap::const_iterator iter = eclose.begin();
iter != eclose.end(); ++iter)
{
Key mid = iter->first;
sem_elem_t w_eps = iter->second;
if (mid == *q) {
// Don't want to add a self-loop
continue;
}
if (F.find(mid) != F.end()) {
// eps path
// *q - - - - - - - - -> (mid)
//
// So *q is effectively final.
result.addFinalState(*q);
}
// eps path (w_eps)
// We have: *q - - - - - - - - - > mid
//
// so we want to look at all outgoing transitions from 'target'
// kp_map_t maps from (source * stack) -> {trans}. Furthermore,
// this is a hash map so is not in any particular order, which
// means we have to loop over the whole dang thing. (If we had an
// explicit list of symbols we could do (for every symbol) but we
// can't.)
for(kp_map_t::const_iterator group = kpmap.begin();
group != kpmap.end(); ++group)
{
if (group->first.first == mid) {
// If we get in here, we're looking at outgoing transitions from
// (source) on *some* symbol. So loop over all the transitions
// from that state, "copy" them to eps_source. If we find another
// epsilon transition, be sure to add it so we do this again in
// the future.
TransSet const & transitions = group->second;
for (TransSet::const_iterator transition = transitions.begin();
transition != transitions.end(); ++transition)
{
Key sym = (*transition)->stack();
Key target = (*transition)->to();
sem_elem_t w_t = (*transition)->weight();
assert(sym == group->first.second);
if (sym == WALI_EPSILON) {
continue;
}
// We have:
// eps path (w_eps) sym (w_t)
// *q - - - - - - - - - > mid ----------> target
//
// and want to make it:
//
// eps path (w_eps) sym (w_t)
// *q - - - - - - - - - > mid ----------> target
// | /\ .
// +--------------------------------------+
// sym (w_eps * w_t)
//
// (We will remove the epsilon transitions later, but above
// we checked to make sure we aren't adding a new one now.)
sem_elem_t w_final = w_eps->extend(w_t);
result.addTrans(*q, sym, target, w_final);
} // for each transition (mid, sym, __)
} // check if the current group matches the mid
} // for each group in kp_map
} // for each mid state in eclose(q)
} // for each q
// Step 2:
// Make a list of all epsilon transitions.
std::stack<ITrans const *> eps_transitions;
for (eps_map_t::const_iterator eps_map_iter=result.eps_map.begin();
eps_map_iter != result.eps_map.end(); ++eps_map_iter)
{
TransSet const & transitions = eps_map_iter->second;
for (TransSet::const_iterator trans_iter = transitions.begin();
trans_iter != transitions.end(); ++trans_iter)
{
ITrans const * trans = *trans_iter;
eps_transitions.push(trans);
if (trans->from() == trans->to()) {
// Not sure if this is true, but I think it is...
std::cerr << "[WARNING] epsilon self loop found in removeEpsilons(); this may go into an infinite loop now\n";
}
}
}
// Step 3:
// Remove all epsilon transitions.
while (eps_transitions.size() > 0) {
ITrans const * trans = eps_transitions.top();
eps_transitions.pop();
assert(trans->stack() == WALI_EPSILON);
if (result.isFinalState(trans->to())) {
result.addFinalState(trans->from());
}
result.erase(trans->from(), WALI_EPSILON, trans->to());
// TODO: delete trans? Who holds ownership?
}
// Step 4:
// Sanity check
for (eps_map_t::const_iterator eps_map_iter=result.eps_map.begin();
eps_map_iter != result.eps_map.end(); ++eps_map_iter)
{
TransSet const & transitions = eps_map_iter->second;
assert(transitions.size() == 0);
}
return result;
}
size_t
WFA::numTransitions() const
{
TransCounter counter;
for_each(counter);
return counter.getNumTrans();
}
//// Prints to 'os' statistics about this WFA.
void WFA::printStatistics(std::ostream & os) const
{
TransCounter counter;
for_each(counter);
std::set<Key> symbols;
for(kp_map_t::const_iterator it = kpmap.begin();
it != kpmap.end(); ++it)
{
symbols.insert(it->first.second);
}
os << "Statistics for WFA " << this << ":\n"
<< " states: " << numStates() << "\n"
<< " accepting states: " << getFinalStates().size() << "\n"
<< " symbols: " << symbols.size() << "\n"
<< " transitions: " << counter.getNumTrans() << "\n";
}
struct RuleAdder : ConstTransFunctor
{
Key p_state;
wpds::WPDS * wpds;
boost::function<bool (ITrans const *)> callback;
boost::function<sem_elem_t (sem_elem_t)> wrapper;
RuleAdder(Key st,
wpds::WPDS * pds,
boost::function<bool (ITrans const *)> cb,
boost::function<sem_elem_t (sem_elem_t)> weight_wrapper)
: p_state(st),
wpds(pds),
callback(cb),
wrapper(weight_wrapper)
{}
virtual void operator()( ITrans const * t )
{
sem_elem_t weight = t->weight();
if (wrapper) {
weight = wrapper(weight);
}
if (callback && callback(t)) {
wpds->add_rule(p_state, t->from(),
p_state, t->to(),
weight);
}
}
};
struct ReverseRuleAdder : RuleAdder
{
ReverseRuleAdder(Key st,
wpds::WPDS * pds,
boost::function<bool (ITrans const *)> cb,
boost::function<sem_elem_t (sem_elem_t)> weight_wrapper)
: RuleAdder(st, pds, cb, weight_wrapper)
{}
virtual void operator()( ITrans const * t )
{
sem_elem_t weight = t->weight();
if (wrapper) {
weight = wrapper(weight);
}
if (callback && callback(t)) {
wpds->add_rule(p_state, t->to(),
p_state, t->from(),
weight);
}
}
};
void
WFA::toWpds(Key p_state,
wpds::WPDS * wpds,
boost::function<bool (ITrans const *)> trans_accept,
bool reverse,
boost::function<sem_elem_t (sem_elem_t)> weight_wrapper) const
{
if (reverse) {
ReverseRuleAdder adder(p_state, wpds, trans_accept, weight_wrapper);
this->for_each(adder);
} else {
RuleAdder adder(p_state, wpds, trans_accept, weight_wrapper);
this->for_each(adder);
}
}
struct AlphabetComputer : ConstTransFunctor
{
std::set<Key> alphabet;
virtual void operator()( ITrans const * t )
{
if (t->stack() != WALI_EPSILON) {
alphabet.insert(t->stack());
}
}
};
std::set<Key>
WFA::alphabet() const
{
AlphabetComputer x;
this->for_each(x);
return x.alphabet;
}
TransSet const *
WFA::outgoingTransSet(Key state, Key symbol) const
{
kp_map_t::const_iterator loc = kpmap.find(KeyPair(state, symbol));
if (loc == kpmap.end()
|| loc->second.size() == 0u)
{
return NULL;
}
return &loc->second;
}
TransSet *
WFA::outgoingTransSet(Key state, Key symbol)
{
kp_map_t::iterator loc = kpmap.find(KeyPair(state, symbol));
if (loc == kpmap.end()
|| loc->second.size() == 0u)
{
return NULL;
}
return &loc->second;
}
std::pair<Key, sem_elem_t>
WFA::endOfEpsilonChain(Key starting_state) const
{
// Get the set of outgoing epsilon transitions
TransSet const * eps_transitions = outgoingTransSet(starting_state, WALI_EPSILON);
if (eps_transitions == NULL
|| eps_transitions->size() != 1u)
{
return std::make_pair(starting_state,
getSomeWeight()->one());
}
// Now check for non-epsilon transitions...
std::set<Key> alpha = alphabet();
for (std::set<Key>::const_iterator iter = alpha.begin();
iter != alpha.end(); ++iter)
{
if (outgoingTransSet(starting_state, *iter) != NULL) {
return std::make_pair(starting_state,
getSomeWeight()->one());
}
}
// OK. Now we can do real work. :-)
ITrans * the_only_outgoing_trans = *(eps_transitions->begin());
// Maybe.
if (the_only_outgoing_trans->to() == starting_state) {
// loop
return std::make_pair(starting_state,
getSomeWeight()->one());
}
std::pair<Key, sem_elem_t> nexts =
endOfEpsilonChain(the_only_outgoing_trans->to());
return std::make_pair(nexts.first,
the_only_outgoing_trans->weight()
->extend(nexts.second));
}
// This function takes a state like
// a eps
// st ----> n1 -----> n4
// | \ b
// c| +---> n2 -----> n5
// V
// n3
// and changes it to
// a
// st ---> n4
// | \ b
// c| +--> n5
// V
// n3
//
// Note that this collapsing can work with epsilon too:
// eps eps
// st ----> n1 ----> n2
// can collapse to
// eps
// st ----> n2
void
WFA::collapseTransitionsForwardFrom(Key state)
{
std::vector<ITrans*> to_add, to_remove;
std::set<Key> alpha = alphabet();
alpha.insert(WALI_EPSILON);
for (std::set<Key>::const_iterator symbol = alpha.begin();
symbol != alpha.end(); ++symbol)
{
if (TransSet * transitions = outgoingTransSet(state, *symbol)) {
for (TransSet::iterator trans = transitions->begin();
trans != transitions->end(); ++trans)
{
assert((*trans)->from() == state);
assert((*trans)->stack() == *symbol);
std::pair<Key, sem_elem_t>
chainEnd = endOfEpsilonChain((*trans)->to());
if (chainEnd.first != (*trans)->to()) {
Trans * newTrans = new Trans(state, *symbol, chainEnd.first,
(*trans)->weight()->extend(chainEnd.second));
to_add.push_back(newTrans);
to_remove.push_back(*trans);
}
}
}
}
for (std::vector<ITrans*>::iterator trans = to_remove.begin();
trans != to_remove.end(); ++trans)
{
assert((*trans)->from() == state);
erase(state, (*trans)->stack(), (*trans)->to());
//delete *trans; // ouch
}
for (std::vector<ITrans*>::iterator trans = to_add.begin();
trans != to_add.end(); ++trans)
{
assert((*trans)->from() == state);
addTrans(*trans);
}
}
void
WFA::removeStatesWithInDegree0()
{
bool removed = true;
do {
removed = false;
std::set<Key> to_remove;
IncomingTransMap_t preds;
for (std::set<Key>::const_iterator state = Q.begin();
state != Q.end(); ++state)
{
preds[*state]; // I am a terrible person. But so are you if
// you remove this without fixing it. :-)
// -eed
}
for (kp_map_t::const_iterator setiter = kpmap.begin();
setiter!= kpmap.end(); ++setiter)
{
for (TransSet::const_iterator titer = setiter->second.begin();
titer != setiter->second.end(); ++titer)
{
preds[(*titer)->to()].push_back(*titer);
}
}
for (IncomingTransMap_t::const_iterator iter = preds.begin();
iter != preds.end(); ++iter)
{
if (iter->second.size() == 0u
&& iter->first != getInitialState())
{
to_remove.insert(iter->first);
}
}
for (std::set<Key>::const_iterator state = to_remove.begin();
state != to_remove.end(); ++state)
{
eraseState(*state);
removed = true;
}
} while (removed);
}
void
WFA::collapseEpsilonChains()
{
for (std::set<Key>::const_iterator state = Q.begin();
state != Q.end(); ++state)
{
collapseTransitionsForwardFrom(*state);
}
removeStatesWithInDegree0();
}
namespace details {
Key get_key(ITrans const * trans)
{
return getKey(trans->stack(), getKey(trans->from(), trans->to()));
//std::stringstream ss;
//ss << "[" << /*trans->from() << "," <<*/ trans->to() << "]";
//return getKey(trans->stack(), trans->to()); //getKey(ss.str()));
}
struct AddTransAsState : ConstTransFunctor {
WFA & m_wfa;
sem_elem_t m_zero;
AddTransAsState(WFA & wfa, sem_elem_t zero)
: m_wfa(wfa)
, m_zero(zero)
{}
void operator() (ITrans const * trans) {
/// Given (Q, delta, Q0, F):
///
/// Q' = delta + {q0}
Key trans_key = get_key(trans);
m_wfa.addState(trans_key, m_zero);
}
};
struct AddInvertedTrans : ConstTransFunctor{
WFA & m_wfa;
sem_elem_t m_one;
Key m_new_q0;
Key m_old_q0;
std::set<Key> const & m_old_f;
Key m_new_qf;
typedef std::vector<ITrans const *> TransVec;
typedef std::map<Key, std::vector<ITrans const *> > TransViewMap;
TransViewMap const & m_trans_view;
AddInvertedTrans(WFA & wfa, sem_elem_t one,
Key old_q0, Key new_q0,
std::set<Key> const & old_f, Key new_qf,
TransViewMap const & trans_view)
: m_wfa(wfa)
, m_one(one)
, m_new_q0(new_q0)
, m_old_q0(old_q0)
, m_old_f(old_f)
, m_new_qf(new_qf)
, m_trans_view(trans_view)
{}
void operator() (ITrans const * trans) {
/// delta' = { ((_,_,q), q, (q,_,_)) | two triples in delta }
/// union { (q0, *, (qq,_,_)) | qq in Q0 and triple in delta }
/// union { ((_,_,f), *, qf) | f in F and triple in delta }
Key trans_key = get_key(trans);
// Let's start with the middle set comprehension:
// { (q0, *, (qq,_,_)) | qq in Q0 and triple in delta }
if (trans->from() == m_old_q0)
m_wfa.addTrans(m_new_q0, WALI_EPSILON, trans_key, m_one);
// And now the third:
// { ((_,_,f), *, qf) | f in F and triple in delta }
if (m_old_f.find(trans->to()) != m_old_f.end())
m_wfa.addTrans(trans_key, WALI_EPSILON, m_new_qf, m_one);
// And now the complicated one:
// { ((_,_,q), q, (q,_,_)) | two triples in delta }
Key q = trans->to();
TransViewMap::const_iterator iter = m_trans_view.find(q);
if (iter != m_trans_view.end()) {
for (TransVec::const_iterator iter_trans = iter->second.begin();
iter_trans != iter->second.end(); ++iter_trans)
{
Key target_trans_key = get_key(*iter_trans);
m_wfa.addTrans(trans_key, q, target_trans_key, m_one);
}
}
}
};
}
WFA
WFA::invertStatesAndTransitions() const
{
using namespace details;
std::map<Key, std::vector<ITrans const *> > trans_view;
for (kp_map_t::const_iterator iter = kpmap.begin();
iter != kpmap.end(); ++iter)
{
TransSet const & transSet = iter->second;
for (TransSet::iterator tsit = transSet.begin();
tsit != transSet.end(); ++tsit)
{
trans_view[(*tsit)->from()].push_back(*tsit);
}
}
sem_elem_t zero = getSomeWeight()->zero();
sem_elem_t one = zero->one();
Key q0 = getKey("start");
Key qf = getKey("accept");
WFA result;
result.addState(q0, zero);
result.addState(qf, zero);
result.setInitialState(q0);
result.addFinalState(qf);
// Sets Q
AddTransAsState tf1(result, zero);
for_each(tf1);
// Sets delta
AddInvertedTrans tf2(result, one,
getInitialState(), q0,
getFinalStates(), qf,
trans_view);
for_each(tf2);
return result;
}
namespace delta
{
WFA
simplify(WFA const & input,
boost::function<DeltaResult (WFA const &)> tester)
{
std::cerr << "WFA's delta::simplify: ";
WFA minimal = input;
bool changed = true;
while (changed) {
changed = false;
std::cerr << "!";
for (std::set<Key>::const_iterator iter = minimal.getStates().begin();
iter != minimal.getStates().end(); ++iter)
{
std::cerr << ".";
WFA test = minimal;
test.eraseState(*iter);
if (tester(test) == Interesting) {
changed = true;
minimal.eraseState(*iter);
break;
}
}
}
std::cerr << "\n";
return minimal;
}
}
} // namespace wfa
} // namespace wali
// Yo emacs!
// Local Variables:
// c-file-style: "ellemtel"
// c-basic-offset: 2
// indent-tabs-mode: nil
// End:
|
/// \file NiCfConstants.hh
/// \brief Definition of constants.
#ifndef NiCfConstants_h
#define NiCfConstants_h 1
#include "globals.hh"
constexpr G4int kDensityNiO = 6.67; // in g/cm3
#endif
|
#pragma once
#include <vector>
#include "AAModel.h"
#include "AACamera.h"
class AAScene
{
public:
AAScene();
~AAScene();
const AACamera* getAciveCamera() const;
const std::vector<AAModel*> getModels() const;
virtual void update() = 0;
protected:
AACamera* camera;
std::vector<AAModel*> objects;
};
|
//信号量
#include <xr_util.h>
namespace xr
{
struct semaphore_t
{
sem_t sem;
int init()
{
if (0 != sem_init(&this->sem, 0, 0))
{
perror("semaphore initialization failed");
return FAIL;
}
return SUCC;
}
inline void wait()
{
::sem_wait(&this->sem);
}
inline void post()
{
::sem_post(&this->sem);
}
void destory()
{
::sem_destroy(&this->sem);
}
virtual ~semaphore_t()
{
this->destory();
}
};
} //end namespace xr
|
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <math.h>
#include<cmath>
#include "mclmcr.h"
#include<complex>
#include <cuComplex.h>
#include<stdlib.h>
#include <stdio.h>
#include <iostream>
#include <windows.h>
//#include<complex.h>
using namespace std;
//cudaError_t theta_calculate_WithCuda(int a, int b);
//定义常量内存
__constant__ double x_begin = (-3.0 / 1000);
__constant__ double z_begin = 27.5 / 1000;
__constant__ double d_x = 0.05 / 1000;
__constant__ double d_z = 0.05 / 1000;
__constant__ double pitch = (3.08e-4);
__constant__ int N_elements = 128;
__constant__ int c = 1540;
__constant__ double theta_threshold = 2.8;
__constant__ int emit_pitch = 1;
__constant__ double t1 = (3.895e-5);
__constant__ int fs = 40000000;
__constant__ int zerolength = 1000;
__device__ void swap_rows(cuDoubleComplex(*Rxx1)[52], int r1, int r2) {
cuDoubleComplex temp[1][52];
int i, j;
for (i = 0; i < 52; i++)
{
temp[0][i] = Rxx1[r1][i];
Rxx1[r1][i] = Rxx1[r2][i];
Rxx1[r2][i] = temp[0][i];
}
/*temp[1] = Rxx1[r1];
Rxx1[r1] = Rxx1[r2];
Rxx1[r2] = temp[1];*/
}
__device__ void scale_row(cuDoubleComplex(*Rxx1)[52], int r, cuDoubleComplex scalar, int L1) {
int i;
for (i = 0; i < L1; i++) {
Rxx1[r][i] = cuCmul(Rxx1[r][i], scalar);
}
}
__device__ void shear_row(cuDoubleComplex(*Rxx1)[52], int r1, int r2, cuDoubleComplex scalar, int L1) {
int i;
for (i = 0; i < L1; i++) {
Rxx1[r1][i] = cuCadd(Rxx1[r1][i], cuCmul(Rxx1[r2][i], scalar));
}
}
__device__ void matrix_inv(cuDoubleComplex(*Rxx1)[52], int L1) {
cuDoubleComplex Rxx1_out[52][52] = { 0.0 };
int i, j, r;
cuDoubleComplex scalar;
cuDoubleComplex shear_needed;
for (i = 0; i < L1; i++)
{
Rxx1_out[i][i] = make_cuDoubleComplex( 1.0,0.0);
}
for (i = 0; i < L1; i++)
{
if ((cuCreal(Rxx1[i][i]) == 0.0) && (cuCimag(Rxx1[i][i]) == 0.0)) {
for (r = i + 1; r < L1; r++)
{
if ((cuCreal(Rxx1[i][i]) != 0.0) || (cuCimag(Rxx1[i][i]) != 0.0))
{
break;
}
}
swap_rows(Rxx1, i, r);
swap_rows(Rxx1_out, i, r);
}
scalar = cuCdiv(make_cuDoubleComplex(1.0, 0.0), Rxx1[i][i]);
scale_row(Rxx1, i, scalar, L1);
scale_row(Rxx1_out, i, scalar, L1);
for (j = 0; j < L1; j++)
{
if (i == j) { continue; }
shear_needed = make_cuDoubleComplex(-cuCreal(Rxx1[j][i]), -cuCimag(Rxx1[j][i]));
shear_row(Rxx1, j, i, shear_needed, L1);
shear_row(Rxx1_out, j, i, shear_needed, L1);
}
}
Rxx1 = Rxx1_out;
}
__device__ void output_beam(int M_elements, int emit_aperture, int L1, int L2, cuDoubleComplex *beamDASDAS, cuDoubleComplex *x_pointer, cuDoubleComplex *wmv1, cuDoubleComplex *wmv2, int idx, int a, int b) {
int l1, l2;
int i, j;
cuDoubleComplex xL[52][52] = { 0.0 };
for (l1 = 0; l1 < M_elements - L1; l1++)
{
for (l2 = 0; l2 < emit_aperture - L2; l2++)
{
for (i = 0; i < L2; i++)
{
for (j = 0; j < L1; j++)
{
xL[i][j] = cuCadd(xL[i][j], x_pointer[idx * 128 * 128 + 128 * (i + l2) + (l1 + j)]);
}
}
}
}
cuDoubleComplex temp[52] = { 0.0 };
for (l1 = 0; l1 < L1; l1++)
{
for (l2 = 0; l2 < L2; l2++)
{
temp[l1] = cuCadd(temp[l1], cuCmul(wmv2[52 * idx + l2], xL[l2][l1]));
}
}
for (int i = 0; i < L1; i++)
{
beamDASDAS[(b - 1) * 121 + (a - 1)] = cuCadd(beamDASDAS[(b - 1) * 121 + (a - 1)], cuCmul(temp[i], wmv1[i]));
}
}
__device__ void weigt_cal_MV(int M_elements, int emit_aperture, cuDoubleComplex *x_pointer, cuDoubleComplex *wmv1, cuDoubleComplex *wmv2, int idx, int L1, int L2)
{
int i, j, k, l;
printf("Have entered into weight_cal_MV function!\n");
cuDoubleComplex Rxx1[52][52] = { 0.0 };
printf("Have finished the definiton of Rxx1[52][52]!\n");
for (l = 0; l < M_elements - L1; l++)
{
printf("Have entered into Rxx1 calculation function!\n");
for (i = 0; i < L1; i++)
{
for (j = 0; j < L1; j++)
{
for (k = 0; k < M_elements; k++)
{
Rxx1[i][j] = cuCadd(Rxx1[i][j],cuCmul(x_pointer[idx * 128 * 128 + (k) * 128 + i + l], cuConj(x_pointer[idx * 128 * 128 + k * 128 + j + l])));
}
}
}
}
printf("Have calculated the Rxx1!\n");
cuDoubleComplex trace = make_cuDoubleComplex(0.0,0.0);
for (i = 0; i < L1; i++)
{
trace = cuCadd(Rxx1[i][i], trace);
}
for (i = 0; i < L1; i++)
{
Rxx1[i][i] = cuCadd(Rxx1[i][i], cuCmul(trace, (make_cuDoubleComplex((double)(0.01 / L1), 0.0))));
}
printf("Have add the trace with Rxx1!\n");
matrix_inv(Rxx1, L1);
printf("Have finished the inversion of Rxx1!\n");
cuDoubleComplex right_value = make_cuDoubleComplex(0.0, 0.0);
for (int i = 0; i < L1; i++)
{
for (int j = 0; j < L1; j++)
{
right_value = cuCadd(right_value, Rxx1[i][j]);
}
}
right_value = cuCdiv(make_cuDoubleComplex(1.0, 0.0), right_value);
for (i = 0; i < L1; i++)
{
for (j = 0; j < L1; j++)
{
wmv1[i + idx * 52] = cuCadd(Rxx1[i][j], wmv1[i + idx * 52]);
}
wmv1[i + idx * 52] = cuCmul(wmv1[i + idx * 52], right_value);
}
printf("Have got the final values of wmv1!\n");
//To now, we have calculated the weight of wmv1, and similarly we should calculate the weights fo wmv2
cuDoubleComplex Rxx2[52][52] = { 0.0 };
for (l = 0; l < M_elements - L2; l++)
{
for (i = 0; i < L2; i++)
{
for (j = 0; j < L2; j++)
{
for (k = 0; k < emit_aperture; k++)
{
Rxx2[i][j] = Rxx2[i][j] = cuCmul(x_pointer[idx * 128 * 128 + k + (i + l) * 128], cuConj(x_pointer[idx * 128 * 128 + k + (j + l) * 128]));
}
}
}
}
trace = make_cuDoubleComplex(0.0, 0.0);
for (i = 0; i < L2; i++)
{
trace = cuCadd(Rxx2[i][i], trace);
}
for (i = 0; i < L1; i++)
{
Rxx2[i][i] = cuCadd(Rxx2[i][i], cuCmul(trace, (make_cuDoubleComplex((double)(0.01 / L2), 0.0))));
}
printf("Have got Rxx2!\n");
matrix_inv(Rxx2, L2);
printf("Have finished the inversion of Rxx2!\n");
right_value = make_cuDoubleComplex(0.0, 0.0);
for (int i = 0; i < L2; i++)
{
for (int j = 0; j < L2; j++)
{
right_value = cuCadd(right_value, Rxx2[i][j]);
}
}
right_value = cuCdiv(make_cuDoubleComplex(1.0, 0.0), right_value);
for (i = 0; i < L2; i++)
{
for (j = 0; j < L2; j++)
{
wmv2[i + idx * 52] = cuCadd(Rxx2[i][j], wmv2[i + idx * 52]);
}
wmv2[i + idx * 52] = cuCmul(wmv2[i + idx * 52], right_value);
}
printf("Have got the final wmv2!\n");
}
__global__ void theta_calculate_WithCuda(cuDoubleComplex *d_init_M1, cuDoubleComplex *beamDASDAS, cuDoubleComplex *x_pointer, cuDoubleComplex *wmv1, cuDoubleComplex *wmv2)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x + blockIdx.y * blockDim.y + threadIdx.y;
int b = (idx / 121) + 1;
int a = (idx - (b - 1) * 121) + 1;
int i;
int k;
int theta_start;
int theta_end;
int M_elements;
int emit_aperture;
int emit_start;
double xp, zp;
double d_t_delay[128];
double d_theta_ctrb[128];
double xr[128];
//printf("a=%d,b=%d\n", a, b);
//printf("d_init_M1 %d is %e,%e\n", idx, cuCreal(d_init_M1[0]), cuCimag(d_init_M1[0]));
double a_begin = -double((N_elements - 1)) / 2 * pitch;
if (idx < 501 * 121)
{
xp = x_begin + d_x * (a - 1);
zp = z_begin + d_z * (b - 1);
/*cudaMalloc(&d_t_delay, 128 * sizeof(double));
cudaMalloc(&d_theta_ctrb, 128 * sizeof(double));
cudaMalloc(&xr, 128 * sizeof(double));*/
//printf("idx=%d \n", idx);
for (i = 0; i < (N_elements); i++)
{
xr[i] = a_begin + pitch * i;
d_t_delay[i] = sqrt(pow((xp - xr[i]), 2) + pow(zp, 2)) / c;
d_theta_ctrb[i] = zp / (abs(xp - xr[i]));
}
//printf("Till for 1\n");
k = 1;
while ((k <= N_elements) && (d_theta_ctrb[k - 1] < theta_threshold))
{
k = k + 1;
}//求出theta_start的值
//printf("Till while 1\n");
if (k == N_elements + 1)
NULL;
//开始求theta_end的值
else
{
theta_start = k;
// cout << "k or theta_start is" << k << endl;
while ((k <= N_elements) && (d_theta_ctrb[k - 1] >= theta_threshold))
{
k = k + 1;
}
if (k == N_elements + 1)
theta_end = k - 1;
else
{
theta_end = k;
}
}
//printf("theta_start=%d,theta_end=%d\n",theta_start,theta_end);
/*cudaFree(d_t_delay);
cudaFree(d_theta_ctrb);*/
int Trans_elements;
M_elements = theta_end - theta_start + 1;
emit_aperture = M_elements;
emit_start = theta_start;
//double index_finished = 0;
int index_1;
int row_v2;
int column_v2;
int temp;
int temp_1;
int temp_2;
//printf("Before 分配x_pointer内存\n");
//cuDoubleComplex x_pointer[128 * 128];//为x数组分配动态内存,记得用完delete,x二维数组,是经过正取延时,并且取正确孔径的,回波矩阵。维度为M_elements*M_elements
double delay_pointer[128];//为delay数组分配动态内存,记得用完delete
int delay_int[128];//为取整后的delay值分配内存。
//printf("After 分配x_pointer内存\n");
//*************接下来计算正确延时和回波矩阵x【M_elements*M_elements】*******************************************//
for (Trans_elements = emit_start; Trans_elements <= (emit_start + emit_pitch * (emit_aperture - 1)); Trans_elements++)
{
for (i = theta_start; i <= theta_end; i++)
{
temp = i - theta_start;
delay_pointer[temp] = d_t_delay[Trans_elements - 1] + d_t_delay[i - 1];
delay_pointer[temp] = delay_pointer[temp] - t1;
delay_pointer[temp] = ((delay_pointer[temp] * fs) + 25.5) + zerolength;
delay_int[temp] = (round)(delay_pointer[temp]);
// int abc = delay_int[temp];
}
//printf("delay_int %d is %d\n", idx,delay_int[0]);//delay_int正确
for (i = theta_start; i <= theta_end; i++)
{
index_1 = (i - theta_start);
row_v2 = delay_int[index_1];//此处计算有误!
column_v2 = (Trans_elements - 1)*N_elements + i - 1;
temp_1 = ((Trans_elements - emit_start) / emit_pitch)*M_elements + i - theta_start;
//x_pointer[temp_1] = init_M1[row_v2*M + (Trans_elements - 1)*N_elements + i-1];//M为v2矩阵的行数
temp_2 = column_v2 * 3534 + row_v2 - 1;
x_pointer[temp_1 + idx * 128 * 128] = d_init_M1[temp_2];//每个线程的x_pointer都分配了128*128的内存,所以下一个线程在全部121*128*128的内存里,其地址要加上idx*128*128
//((Trans_elements - 1)*N_elements + i - 1)*M+row_v2
}
}
double subarray_length = 0.4;
int L1 = rint(M_elements*subarray_length);
int L2 = rint(emit_aperture*subarray_length);
printf("Begin to use weight_cal_MV function!\n");
weigt_cal_MV(M_elements, emit_aperture, x_pointer, wmv1, wmv2, idx,L1,L2);
printf("Have finished calculating the weights!\n");
for (i = 0; i < 52; i++)
{
printf("wmv1[%d] is %f,%f\n", i, cuCreal(wmv1[idx * 52 + i]), cuCimag(wmv1[idx * 52 + i]));
}
//output_beam(beamDASDAS,x_pointer,wmv1,wmv2,idx);
output_beam(M_elements, emit_aperture, L1, L2, beamDASDAS, x_pointer, wmv1, wmv2, idx, a, b);
//printf("x_pointer[0] of thread %d is %e,%e\n", idx, cuCreal(x_pointer[0+ idx * 128 * 128]), cuCimag(x_pointer[0+ idx * 128 * 128]));
//*************计算延时和回波矩阵完毕*********************************************************************//
//*************接下来计算本像素点的beamDASDAS*******************************************//
// for (i = 0; i < M_elements; i++)
// {
// int j;
// for (j = 0; j < M_elements; j++)
// {
// cuDoubleComplex temp_1 = make_cuDoubleComplex(0, 0);
// temp_1 = cuCadd(x_pointer[i*M_elements + j + (idx * 128 * 128)], beamDASDAS[(b - 1) * 121 + (a - 1)]);//注意此处x_pointer的地址也加上了idx*128*128
// beamDASDAS[(b - 1) * 121 + (a - 1)] = temp_1;
// }
// }
// beamDASDAS[(b - 1) * 121 + (a - 1)] = make_cuDoubleComplex(cuCreal(beamDASDAS[(b - 1) * 121 + (a - 1)]) / ((double)(M_elements*M_elements)), cuCimag(beamDASDAS[(b - 1) * 121 + (a - 1)]) / ((double)(M_elements*M_elements)));
//printf("beam %d is %e,%e\n", ((b - 1) * 121 + (a - 1)), cuCreal(beamDASDAS[(b - 1) * 121 + (a - 1)]), cuCimag(beamDASDAS[(b - 1) * 121 + (a - 1)]));
}
}
//核函数定义结束!
/*********************************************核函数定义结束***************************************************************************/
/*********Begin for the MV algorithms**********************/
#include "mat.h"
static MATFile *pMF = NULL;
static mxArray *pA = NULL;
static MATFile *pMF_out = NULL;
static mxArray *pA_out = NULL;
static int TOTAL_ELEMENTS = (3534 * 16384);
int i;
int main()
{
/*******************************************数据预处理部分---将v2的complex数据读进来**************************************/
double *init_imaginary;
double *init_real;
cuDoubleComplex * init_M1 = new cuDoubleComplex[3534 * 16384];
//complex<double> *init_M1;
pMF = matOpen("D:\\WenshuaiZhao\\ProjectFiles\\VisualStudioFiles\\Ultrasound_GPU\\GPU_Data\\v2.mat", "r");//打开MAT文件,返回文件指针
pA = matGetVariable(pMF, "v2");//获取v2.mat文件里的变量
init_real = (double*)mxGetPr(pA);
init_imaginary = (double*)mxGetPi(pA);
//init_M1 = (complex<double>*)mxGetData(pA);
//cuDoubleComplex temp;
for (i = 0; i < TOTAL_ELEMENTS; i++)
{
//complex<double> temp(init_real[i], init_imaginary[i]);
init_M1[i] = make_cuDoubleComplex(init_real[i], init_imaginary[i]);
}//将从v2读出的实部和虚部重新组合在一起,放入init_M1.
cuDoubleComplex * d_init_M1;
cudaMalloc(&d_init_M1, 3534 * 16384 * sizeof(cuDoubleComplex));
for (i = 0; i < 10; i++)
{
cout << "init_M1_"
<< i
<< "="
<< cuCreal(init_M1[i]) << "," << cuCimag(init_M1[i]) << endl;
}//验证init_M1的数据同v2的原始数据是一致的,复数。
//for (i = 0; i < 10; i++)
//{
// printf("init_M1 %d is %e,%e\n", i,cuCreal(init_M1[i]), cuCimag(init_M1[i]));
//}//验证init_M1的数据同v2的原始数据是一致的,复数。
cudaMemcpy(d_init_M1, init_M1, 3534 * 16384 * sizeof(cuDoubleComplex), cudaMemcpyHostToDevice);
printf("已经将init_M1考培到GPU全局内存\n");
delete[] init_M1;
/*******************************************数据预处理部分结束*********************************************************/
//size_t size = 501 * 121 * sizeof(int);
dim3 threadsPerBlock(1, 1);
dim3 numBlocks(1, 1);
//由于线程内的内存不足以存放x_pointer的数据,因此将其放在全局内存
cuDoubleComplex * x_pointer;
cudaMalloc(&x_pointer, 128 * 128 * (1 * 1) * sizeof(cuDoubleComplex));//121是线程总数
//分配host beamDASDAS内存;
cuDoubleComplex *h_beamDASDAS = new cuDoubleComplex[1 * 1];
memset(h_beamDASDAS, 0, sizeof(h_beamDASDAS));
//Begin to distribute the weight memory
cuDoubleComplex *wmv1;
cuDoubleComplex *wmv2;
cudaMalloc(&wmv1, (1*1) * 52 * sizeof(cuDoubleComplex));
cudaMemset(wmv1, 0, sizeof(wmv1));
cudaMalloc(&wmv2, (1*1) * 52 * sizeof(cuDoubleComplex));
cudaMemset(wmv2, 0, sizeof(wmv2));
//分配device的beamDASDAS内存;
cuDoubleComplex *beamDASDAS;
cudaMalloc(&beamDASDAS, 1 * 1 * sizeof(cuDoubleComplex));
/* int *d_theta_start;
int *d_theta_end;
int *h_theta_start = new int[60621];
int *h_theta_end = new int[60621];
printf("h_theta_start[0]=%d\n", h_theta_start[0]);
cudaMalloc(&d_theta_start, size);
cudaMalloc(&d_theta_end, size);
cudaError_t error = cudaGetLastError();
printf("内存分配完毕...\n", cudaGetErrorString(error));
printf("开始调用核函数...\n", cudaGetErrorString(error)); */
DWORD time_kernel = GetTickCount(); //获取毫秒级数目
theta_calculate_WithCuda << <numBlocks, threadsPerBlock >> > (d_init_M1, beamDASDAS, x_pointer,wmv1,wmv2);
//theta_calculate_WithCuda << <(1,1), (1,1) >> >(d_theta_start, d_theta_end);
cudaDeviceSynchronize();
cout << "核函数执行共用了:" << GetTickCount() - time_kernel << "毫秒" << endl;
cudaError_t error = cudaGetLastError();
printf("CUDA error: %s\n", cudaGetErrorString(error));
printf("核函数调用完毕...\n", cudaGetErrorString(error));
cudaMemcpy(h_beamDASDAS, beamDASDAS, 121 * sizeof(cuDoubleComplex), cudaMemcpyDeviceToHost);
//cudaMemcpy(h_theta_end, d_theta_end, 60621 * sizeof(int), cudaMemcpyDeviceToHost);
//cudaFree(d_theta_start);
cudaFree(wmv1);
cudaFree(wmv2);
cudaFree(beamDASDAS);
for (int i = 0; i < 1; i++)
{
printf("h_beamDASDAS[%d] is %e,%e\n", i, cuCreal(h_beamDASDAS[i]), cuCimag(h_beamDASDAS[i]));
}
cudaDeviceReset();
delete[] h_beamDASDAS;
getchar();
/* delete[] h_theta_start;
delete[] h_theta_end; */
}
|
//: C10:Statinit.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Zasieg inicjatora skladowej statycznej
#include <iostream>
using namespace std;
int x = 100;
class WithStatic {
static int x;
static int y;
public:
void print() const {
cout << "WithStatic::x = " << x << endl;
cout << "WithStatic::y = " << y << endl;
}
};
int WithStatic::x = 1;
int WithStatic::y = x + 1;
// WithStatic::x NIE ::x
int main() {
WithStatic ws;
ws.print();
} ///:~
|
#include "stdafx.h"
#include "SecondStage.h"
#include "Random.h"
#include "ThirdStage.h"
#include "GameManager.h"
SecondStage::SecondStage() : damageTimer(0, .25f), wispNum(10)
{
background = new ZeroSprite("Resource/UI/Background/background.png");
ui = new UIManager();
for (int i = 0; i < 10; i++)
{
Wisp* wisp = new Wisp();
wisp->SetPos(RandomInt(background->Pos().x + 130, background->Pos().x + background->Width() - 130), RandomInt(background->Pos().y + 130, background->Pos().y + background->Height() - 130));
wispList.push_back(wisp);
PushScene(wisp);
}
player = new PlayerCharacter();
PushScene(player);
PushScene(ui);
failBackground->SetColorA(0);
failSprite->SetColorA(0);
damageText->SetString("Damage : " + to_string((int)player->attackPower));
healthText->SetString("Health: " + to_string((int)player->health));
speedText->SetString("Speed : " + to_string((int)player->speed));
background->SetPos(640 - background->Width() * 0.5f, 355 - background->Height() * 0.5f);
}
void SecondStage::Update(float eTime)
{
ZeroIScene::Update(eTime);
for (auto w : wispList)
{
w->Update(eTime);
w->Follow(player, w, w->speed, eTime, w->isAlive);
if (w->IsCollision(player)) {
w->Attack(player, eTime);
}
if (w->isDamaged)
ui->EnemyUI(w);
}
item->Update(eTime);
player->Update(eTime);
ui->PlayerUI(player);
CheckOut(eTime);
printf("player stamina : %.2f\n", player->stamina);
printf("%d\n", GameManager::GetInstance()->itemType);
}
void SecondStage::Render()
{
ZeroIScene::Render();
background->Render();
for (auto w : wispList)
{
w->Render();
}
player->Render();
if (wispNum == 0)
item->Render();
damageText->Render();
healthText->Render();
speedText->Render();
ui->healthBar->Render();
ui->healthFill->Render();
ui->staminaBar->Render();
ui->staminaFill->Render();
for (auto w : wispList)
{
if (w->isDamaged && w->health < 100)
{
ui->enemyHealthBar->Render();
ui->enemyHealthFill->Render();
}
}
failBackground->Render();
failSprite->Render();
}
void SecondStage::PopStage()
{
}
void SecondStage::CheckOut(float eTime)
{
for (auto w = wispList.begin(); w != wispList.end();)
{
(*w)->Damage(player, eTime);
if (!(*w)->isAlive)
{
wispNum--;
PopScene(*w);
wispList.erase(w++);
}
w++;
}
if (wispNum == 0) {
if (IsCollision(player, item)) {
GameManager::GetInstance()->itemType = item->type;
PopStage();
ZeroSceneMgr->ChangeScene(new ThirdStage());
}
}
ShowResult(player, eTime);
printf("player health : %.2f\n", player->health);
}
|
#ifndef __SERENDEROBJECT_H__
#define __SERENDEROBJECT_H__
#include "SEMath.h"
class SERenderService;
template <class T> class SERenderServiceInternals;
struct SEROType
{
typedef enum {MODEL_RO, PRIMITIVE_RO, CAMERA_RO, LIGHT_RO, FONT_RO, NUM_ROS} tRenderObject;
};
template <class T> class SERenderObject
{
friend class SERenderService;
public:
const SEROType::tRenderObject &objectType;
const SEVec4<T> &translation;
const SEQuaternion<T> &rotation;
const T &scale;
SERenderObject<T> &setTranslation(T x, T y, T z) { t_.vec(x,y,z,(T)1); return(*this); }
SERenderObject<T> &setTranslation(const SEVec3<T> &t) { t_=t; return(*this); }
SERenderObject<T> &setTranslation(const SEVec4<T> &t) { t_=t; return(*this); }
SERenderObject<T> &setTranslation(const SEMat4<T> &t) { return setTranslation(t[3],t[7],t[11],(T)1); }
SERenderObject<T> &setPosition(T x, T y, T z) { return setTranslation(x,y,z); }
SERenderObject<T> &setPosition(const SEVec3<T> &t) { return setTranslation(t); }
SERenderObject<T> &setPosition(const SEVec4<T> &t) { return setTranslation(t); }
SERenderObject<T> &setPosition(const SEMat4<T> &t) { return setTranslation(t); }
SERenderObject<T> &setPos(T x, T y, T z) { return setTranslation(x,y,z); }
SERenderObject<T> &setPos(const SEVec3<T> &t) { return setTranslation(t); }
SERenderObject<T> &setPos(const SEVec4<T> &t) { return setTranslation(t); }
SERenderObject<T> &setPos(const SEMat4<T> &t) { return setTranslation(t); }
SERenderObject<T> &setX(T x) { t_.x=x; return(*this); }
SERenderObject<T> &setY(T y) { t_.y=y; return(*this); }
SERenderObject<T> &setZ(T z) { t_.z=z; return(*this); }
SERenderObject<T> &setPosX(T x) { t_.x=x; return(*this); }
SERenderObject<T> &setPosY(T y) { t_.y=y; return(*this); }
SERenderObject<T> &setPosZ(T z) { t_.z=z; return(*this); }
SERenderObject<T> &translateBy(T x, T y, T z) { t_[0]+=x; t_[1]+=y; t_[2]+=z; return(*this); }
SERenderObject<T> &translateBy(const SEVec3<T> &dt) { t_+=dt; return(*this); }
SERenderObject<T> &translateBy(const SEVec4<T> &dt) { t_+=dt; return(*this); }
SERenderObject<T> &translateBy(const SEMat4<T> &dt) { return translateBy(dt[3],dt[7],dt[11]); }
SERenderObject<T> &translateBy(const SEVec3<T> &dir, T len) { return translateBy(dir.normal()*len); }
SERenderObject<T> &setRotation(const SEQuaternion<T> &r) { r_=r; return(*this); }
SERenderObject<T> &rotateBy(const SEQuaternion<T> &r) { return setRotation(r_.rotate(r)); }
SERenderObject<T> &rotateByDegrees(const SEVec3<T> &axis, T angle) { return setRotation(r_.rotateByDegrees(angle, axis)); }
SERenderObject<T> &rotateByDegrees(T x, T y, T z, T angle) { return setRotation(r_.rotateByDegrees(angle, SEVec3<T>(x,y,z))); }
SERenderObject<T> &rotateByRadians(const SEVec3<T> &axis, T angle) { return setRotation(r_.rotateLocally(angle, axis)); }
SERenderObject<T> &rotateByRadians(T x, T y, T z, T angle) { return setRotation(r_.rotateLocally(angle, SEVec3<T>(x,y,z))); }
SERenderObject<T> &setScale(T s) { s_=s; return(*this); }
SERenderObject<T> &scaleBy(T ds) { s_*=ds; return(*this); }
SERenderObject<T> &orbit(const SEVec4<T> &f, const SEVec3<T> &u, T a) { t_.orbit(f,u,a); return(*this); }
SERenderObject<T> &rotateAround(const SEVec4<T> &f, const SEVec3<T> &u, T a) { t_.rotateAround(f,u,a); return(*this); }
SERenderObject<T> &orbitByDegrees(const SEVec4<T> &f, const SEVec3<T> &u, T a) { t_.orbitByDegrees(f,u,a); return(*this); }
SERenderObject<T> &rotateAroundByDegrees(const SEVec4<T> &f, const SEVec3<T> &u, T a) { t_.rotateAroundByDegrees(f,u,a); return(*this); }
SEMat4<T> getScaleMatrix() const { return SEMat4<T>(s_,0,0,0,
0,s_,0,0,
0,0,s_,0,
0,0,0, 1); }
SEMat4<T> getRotationMatrix() const { return r_.mat4(); }
SEMat4<T> getTranslationMatrix() const { return SEMat4<T>(1,0,0,t_.x,
0,1,0,t_.y,
0,0,1,t_.z,
0,0,0, 1); }
SEMat4<T> getModelMatrix() const { return getTranslationMatrix()*getRotationMatrix()*getScaleMatrix(); }
SEMat4<T> getInverseModelMatrix() const { return getModelMatrix().invert(); }
protected:
SERenderObject(SEROType::tRenderObject rt) : rt_(rt), t_(), r_(), s_(1), objectType(rt_), translation(t_), rotation(r_), scale(s_) {}
virtual ~SERenderObject() {}
virtual void preRender(const SERenderServiceInternals<T> &rs) const {}
virtual void applyTransformation(const SERenderServiceInternals<T> &rs) const {}
virtual void applyMaterial(const SERenderServiceInternals<T> &rs) const {}
virtual void draw(const SERenderServiceInternals<T> &rs) const = 0;
virtual void clearMaterial(const SERenderServiceInternals<T> &rs) const {}
virtual void clearTransformation(const SERenderServiceInternals<T> &rs) const {}
virtual void postRender(const SERenderServiceInternals<T> &rs) const {}
virtual void render(const SERenderServiceInternals<T> &rs) const { this->preRender(rs); this->applyTransformation(rs); this->applyMaterial(rs); this->draw(rs); this->clearMaterial(rs); this->clearTransformation(rs); this->postRender(rs); }
private:
SEROType::tRenderObject rt_;
SEVec4<T> t_;
SEQuaternion<T> r_;
T s_;
};
#endif // __SERENDEROBJECT_H__
|
#pragma once
#include "GameObject.h"
#include "OBJLoader.h"
#include <xnamath.h>
class Car
{
private:
XMFLOAT3 pos;
public:
int number;
GameObject wheelFrontLeft;
GameObject wheelFrontRight;
GameObject wheelBackLeft;
GameObject wheelBackRight;
GameObject carBody;
ID3D11ShaderResourceView* g_wheelTexture;
ID3D11ShaderResourceView* g_bodyTexture;
Car();
~Car();
void CarInit(ID3D11Device *_pd3dDevice);
void loadTextures(ID3D11Device *_pd3dDevice, int i);
void Update(float t);
XMFLOAT4X4 getWorld(GameObject t);
void Draw(ConstantBuffer * CB, ID3D11Device * pd3dDevice, ID3D11DeviceContext * pImmediateContext);
};
|
// Created on: 1993-01-09
// Created by: CKY / Contract Toubro-Larsen ( TCD )
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESGraph_HighLight_HeaderFile
#define _IGESGraph_HighLight_HeaderFile
#include <Standard.hxx>
#include <Standard_Integer.hxx>
#include <IGESData_IGESEntity.hxx>
class IGESGraph_HighLight;
DEFINE_STANDARD_HANDLE(IGESGraph_HighLight, IGESData_IGESEntity)
//! defines IGESHighLight, Type <406> Form <20>
//! in package IGESGraph
//!
//! Attaches information that an entity is to be
//! displayed in some system dependent manner
class IGESGraph_HighLight : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESGraph_HighLight();
//! This method is used to set the fields of the class
//! HighLight
//! - nbProps : Number of property values (NP = 1)
//! - aHighLightStatus : HighLight Flag
Standard_EXPORT void Init (const Standard_Integer nbProps, const Standard_Integer aHighLightStatus);
//! returns the number of property values in <me>
Standard_EXPORT Standard_Integer NbPropertyValues() const;
//! returns 0 if <me> is not highlighted(default),
//! 1 if <me> is highlighted
Standard_EXPORT Standard_Integer HighLightStatus() const;
//! returns True if entity is highlighted
Standard_EXPORT Standard_Boolean IsHighLighted() const;
DEFINE_STANDARD_RTTIEXT(IGESGraph_HighLight,IGESData_IGESEntity)
protected:
private:
Standard_Integer theNbPropertyValues;
Standard_Integer theHighLight;
};
#endif // _IGESGraph_HighLight_HeaderFile
|
#include "global.h"
void emit(int t, int tval) {
switch(t) {
case '+': case '-': case '*': case '/':
printf("%c\n", t); break;
case DIV:
printf("DIV\n"); break;
case MOD:
printf("MOD\n"); break;
case NUM:
printf("%d\n", tval); break;
case ID:
printf("%s\n", symtable[tval].lexptr); break;
default:
printf("token %d, tokenval %d\n", t, tval);
}
}
|
/* Big Easy Driver motor controller firmware. Input a runtime and watch her go!
By Mike Bardwell based on code from Toni Klopfenstein and Tom Igoe
Successfull tested up to 100 seconds of runtime
*/
String inString = ""; // string to hold input
long timer, runtime; // Motor hold time variables
//Declare motor pins
#define stp 2
#define dir 3
#define MS1 4
#define MS2 5
#define MS3 6
#define EN 7
void setup() {
// Declare motor pins as outputs
pinMode(stp, OUTPUT);
pinMode(dir, OUTPUT);
pinMode(MS1, OUTPUT);
pinMode(MS2, OUTPUT);
pinMode(MS3, OUTPUT);
pinMode(EN, OUTPUT);
resetBEDPins(); //Set step, direction, microstep and enable pins to default states
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// send an intro:
Serial.println("\n\nPlease enter a runtime in seconds(+integers only): ");
Serial.println();
}
//Main loop
void loop() {
// Read serial input:
while (Serial.available() > 0) {
int inChar = Serial.read();
if (isDigit(inChar)) {
// convert the incoming byte to a char
// and add it to the string:
inString += (char)inChar;
}
// if you get a newline, print the string,
// then the string's value:
if (inChar == '\n') {
Serial.print("Runtime Integer Inputted: ");
Serial.println(inString.toInt());
timer = millis(); runtime = inString.toInt()*1000;
while (millis() - timer < runtime) {
// Serial.println(millis()-timer);
StepForwardDefault();
}
// clear the string for new input:
inString = "";
resetBEDPins();
Serial.println("\n\nPlease enter a new runtime in seconds(+integers only): ");
Serial.println();
}
}
}
//Reset Big Easy Driver pins to default states
void resetBEDPins()
{
digitalWrite(stp, LOW);
digitalWrite(dir, LOW);
digitalWrite(MS1, LOW);
digitalWrite(MS2, LOW);
digitalWrite(MS3, LOW);
digitalWrite(EN, HIGH);
}
//Default microstep mode function
void StepForwardDefault()
{
digitalWrite(dir, LOW); //Pull direction pin low to move "forward"
digitalWrite(MS1, LOW); digitalWrite(MS2, LOW); digitalWrite(MS3, LOW);
digitalWrite(stp,HIGH); //Trigger one step forward
delayMicroseconds(50);
digitalWrite(stp,LOW); //Pull step pin low so it can be triggered again
delayMicroseconds(50);
}
|
#ifndef JUGADOR_H
#define JUGADOR_H
#include "Padre.h"
#include "Plataforma.h"
#include "PlataformaInvisible.h"
#include "Enemigo.h"
#include "Bomba.h"
class Jugador : public Padre
{
public:
int xvel, yvel, xacc, yacc, xCamara, yCamara, cVel, cVel2, score;
bool suelo, saltando, colD, moviendo, gameOver, perdiste;
Jugador();
virtual ~Jugador();
void mostrar(SDL_Surface* screen, int xMapa, int yMapa);
void mover(vector<Enemigo*> enemigos, vector<Plataforma*> plataformas, vector<Tile*> tiles, int xMapa, int yMapa, Sint16* Camara, int *xMap);
void saltar();
void setMoviendo(bool b);
void setFrame(char direction);
protected:
private:
static const int sprites = 11;
SDL_Rect clips[sprites];
double frame;
};
#endif // JUGADOR_H
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2009-2011.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <fwCore/base.hpp>
#include <fwData/PatientDB.hpp>
#include <fwData/Patient.hpp>
#include <fwData/Study.hpp>
#include <fwData/Acquisition.hpp>
#include <fwData/Image.hpp>
#include <fwTools/Factory.hpp>
#include "itkIO/ImageReader.hpp"
#include "itkIO/JpgPatientDBReader.hpp"
namespace itkIO
{
//------------------------------------------------------------------------------
JpgPatientDBReader::JpgPatientDBReader() :
::fwData::location::enableFolder< ::fwDataIO::reader::IObjectReader >(this)
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
JpgPatientDBReader::~JpgPatientDBReader()
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
void JpgPatientDBReader::searchRecursivelyInrFile( const ::boost::filesystem::path & path, ::std::vector< ::boost::filesystem::path > & inrFiles )
{
for(boost::filesystem::directory_iterator it(path); it != boost::filesystem::directory_iterator(); ++it)
{
if( ::boost::filesystem::is_directory(*it) )
{
searchRecursivelyInrFile(*it,inrFiles);
}
else
{
#if BOOST_FILESYSTEM_VERSION > 2
std::string fileStr = (*it).path().string();
#else
std::string fileStr = (*it).string();
#endif
if ( fileStr.size() > 7 )
{
std::string ext1 = fileStr.substr(fileStr.size()-4,4);
std::string ext2 = fileStr.substr(fileStr.size()-5,5);
if( ext1 == ".jpg" || ext1 == ".JPG" || ext1 == ".jpeg" || ext1 == ".JPEG" )
{
#if BOOST_FILESYSTEM_VERSION > 2
OSLM_DEBUG( "JPEG File Found : " << it->path().string() );
#else
OSLM_DEBUG( "JPEG File Found : " << it->string() );
#endif
inrFiles.push_back(*it);
}
}
}
}
}
//------------------------------------------------------------------------------
std::string JpgPatientDBReader::findCommonPath( ::std::vector< ::boost::filesystem::path > & inrFilePathes )
{
bool newCommonLetterFound = true;
unsigned int minimunPathSize = inrFilePathes[0].string().size();
for ( ::std::vector< ::boost::filesystem::path >::iterator inrFilePath = inrFilePathes.begin();
inrFilePath != inrFilePathes.end();
inrFilePath++ )
{
if ( minimunPathSize > inrFilePath->string().size() )
{
minimunPathSize = inrFilePath->string().size();
}
}
std::string str = "";
unsigned int cmpt = 0;
while( newCommonLetterFound && minimunPathSize != cmpt )
{
str = inrFilePathes[0].string().substr(0,cmpt);
for ( ::std::vector< ::boost::filesystem::path >::iterator inrFilePath = inrFilePathes.begin();
inrFilePath != inrFilePathes.end();
inrFilePath++ )
{
if ( inrFilePath->string().substr(0,cmpt) != str )
{
newCommonLetterFound = false;
}
}
cmpt++;
}
int indexA = str.find_last_of("\\");
int indexB = str.find_last_of("/");
int index = 0;
if ( -1 != indexA )
{
index = indexA + 1;
}
if ( -1 != indexB && indexB > index)
{
index = indexB + 1 ;
}
OSLM_DEBUG("JpgPatientDBReader::findCommonPath : CommonPath = " << str.substr(0,index));
return str.substr(0,index);
}
//------------------------------------------------------------------------------
::fwData::Patient::sptr JpgPatientDBReader::createPatient( const ::boost::filesystem::path inrFilePath, int commonPathSize )
{
::fwData::Image::NewSptr img;
::itkIO::ImageReader::NewSptr reader;
reader->setObject(img);
reader->setFile(inrFilePath);
reader->read();
::fwData::Acquisition::NewSptr acq;
::fwData::Study::NewSptr study;
::fwData::Patient::NewSptr patient;
acq->setImage(img);
study->addAcquisition(acq);
patient->addStudy(study);
patient->setCRefName( inrFilePath.string().substr(commonPathSize,-1) );
return patient;
}
//------------------------------------------------------------------------------
void JpgPatientDBReader::read()
{
SLM_TRACE_FUNC();
assert( ::boost::filesystem::exists( getFolder() ) );
::std::vector< ::boost::filesystem::path > inrFilePathes;
searchRecursivelyInrFile( getFolder(), inrFilePathes );
if ( inrFilePathes.size() > 0 )
{
std::string commonPath = findCommonPath(inrFilePathes);
int commonPathSize = commonPath.size();
float numFile = 0;
for ( ::std::vector< ::boost::filesystem::path >::iterator inrFilePath = inrFilePathes.begin();
inrFilePath != inrFilePathes.end();
inrFilePath++ )
{
getConcreteObject()->addPatient( createPatient( *inrFilePath, commonPathSize ) );
notifyProgress( ++numFile*1.0/inrFilePathes.size(), inrFilePath->string() );
}
}
}
//------------------------------------------------------------------------------
} // namespace itkIO
|
/**
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include "particle_filter.h"
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <string>
#include <vector>
#include "helper_functions.h"
using std::string;
using std::vector;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
/**
* TODO: Set the number of particles. Initialize all particles to
* first position (based on estimates of x, y, theta and their uncertainties
* from GPS) and all weights to 1.
* TODO: Add random Gaussian noise to each particle.
* NOTE: Consult particle_filter.h for more information about this method
* (and others in this file).
*/
num_particles = 100; // TODO: Set the number of particles
// Create a normal distribution for x,y,theta with the associated variances
std::default_random_engine gen;
std::normal_distribution<double> distribution_x(x, std[0]);
std::normal_distribution<double> distribution_y(y, std[1]);
std::normal_distribution<double> distribution_theta(theta, std[2]);
//Create a vector of empty particles
for(int i=0; i<num_particles; i++)
{
Particle particle{};
particles.emplace_back(particle);
}
// Set all the particles to initialization values sampling from the gaussian distribution
for(int i=0; i<num_particles; i++)
{
particles.at(i).id = i;
particles.at(i).x = distribution_x(gen);
particles.at(i).y = distribution_y(gen);
particles.at(i).theta = distribution_theta(gen);
particles.at(i).weight = 1.0;
weights.emplace_back(particles.at(i).weight);
}
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[],
double velocity, double yaw_rate) {
/**
* TODO: Add measurements to each particle and add random Gaussian noise.
* NOTE: When adding noise you may find std::normal_distribution
* and std::default_random_engine useful.
* http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
* http://www.cplusplus.com/reference/random/default_random_engine/
*/
// Create a normal distribution for x,y,theta with the associated variances
std::default_random_engine gen;
std::normal_distribution<double> distribution_x(0.0, std_pos[0]);
std::normal_distribution<double> distribution_y(0.0, std_pos[1]);
std::normal_distribution<double> distribution_theta(0.0, std_pos[2]);
//Implement bycicle model prediction for each particle
for(int i=0; i<num_particles; i++)
{
if (std::abs(yaw_rate) < 0.00001) //this if-else is to handle also cases where the particle has constant yaw (i.e. zero yaw rate)
{
particles.at(i).x = particles.at(i).x + velocity*delta_t*cos(particles.at(i).theta) + distribution_x(gen);
particles.at(i).y = particles.at(i).y + velocity*delta_t*sin(particles.at(i).theta) + distribution_y(gen);
particles.at(i).theta = particles.at(i).theta + distribution_theta(gen);
}
else
{
particles.at(i).x = particles.at(i).x + (velocity/yaw_rate)*(sin(particles.at(i).theta+(yaw_rate*delta_t)) - sin(particles.at(i).theta)) + distribution_x(gen);
particles.at(i).y = particles.at(i).y + (velocity/yaw_rate)*(cos(particles.at(i).theta) - cos(particles.at(i).theta+(yaw_rate*delta_t))) + distribution_y(gen);
particles.at(i).theta = particles.at(i).theta + yaw_rate*delta_t + distribution_theta(gen);
}
}
}
void ParticleFilter::dataAssociation(vector<LandmarkObs> landmarks,
vector<LandmarkObs>& observations) {
/**
* TODO: Find the landmark that is closest to each
* observed measurement and assign the observed measurement to this
* particular landmark.
* NOTE: this method will NOT be called by the grading code. But you will
* probably find it useful to implement this method and use it as a helper
* during the updateWeights phase.
*/
double min_dist{std::numeric_limits<double>::max()};
for (size_t i = 0; i < observations.size(); i++)
{
for (size_t j = 0; j < landmarks.size(); j++)
{
double current_dist{dist(observations[i].x, observations[i].y, landmarks[j].x, landmarks[j].y)};
if (current_dist < min_dist)
{
observations[i].id = landmarks[j].id;
min_dist = current_dist;
}
}
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
const vector<LandmarkObs> &observations,
const Map &map_landmarks) {
/**
* TODO: Update the weights of each particle using a mult-variate Gaussian
* distribution. You can read more about this distribution here:
* https://en.wikipedia.org/wiki/Multivariate_normal_distribution
* NOTE: The observations are given in the VEHICLE'S coordinate system.
* Your particles are located according to the MAP'S coordinate system.
* You will need to transform between the two systems. Keep in mind that
* this transformation requires both rotation AND translation (but no scaling).
* The following is a good resource for the theory:
* https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
* and the following is a good resource for the actual equation to implement
* (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html
*/
double sum_all_weights{0.0};
for (int i = 0; i < num_particles; i++)
{
//Transform measurements in map coordinate system (homogeneous transformation) for each particle
vector<LandmarkObs> observations_in_map_ref_system{};
for (size_t j = 0; j < observations.size(); j++)
{
LandmarkObs current_map_obs;
current_map_obs.id = observations[j].id;
current_map_obs.x = particles[i].x + (cos(particles[i].theta) * observations[j].x) - (sin(particles[i].theta) * observations[j].y);
current_map_obs.y = particles[i].y + (sin(particles[i].theta) * observations[j].x) + (cos(particles[i].theta) * observations[j].y);
observations_in_map_ref_system.emplace_back(current_map_obs);
}
//Find the landmarks (on map) in the sensor range for each particle:
//The distance between particle and landmark has to be smaller than sensor_range
vector<LandmarkObs> seen_landmarks{};
for (size_t j = 0; j < map_landmarks.landmark_list.size(); j++)
{
double particle2landmark_dist{dist(particles[i].x, particles[i].y, map_landmarks.landmark_list[j].x_f, map_landmarks.landmark_list[j].y_f)};
if (particle2landmark_dist < sensor_range)
{
seen_landmarks.emplace_back(LandmarkObs{map_landmarks.landmark_list[j].id_i, map_landmarks.landmark_list[j].x_f, map_landmarks.landmark_list[j].y_f});
}
}
//Data association: associate the map landmarks id (in range) with the observations
dataAssociation(seen_landmarks, observations_in_map_ref_system);
//Update the weight for each particle
particles[i].weight = 1.0;
for (size_t j = 0; j < observations_in_map_ref_system.size(); j++)
{
for (size_t k = 0; k < seen_landmarks.size(); k++)
{
if (seen_landmarks[k].id == observations_in_map_ref_system[j].id) //Update weight when the closest landmark is found
{
particles[i].weight = particles[i].weight*multiv_prob(std_landmark[0], std_landmark[1], observations_in_map_ref_system[j].x, observations_in_map_ref_system[j].y, seen_landmarks[k].x, seen_landmarks[k].y);
break;
}
}
}
sum_all_weights = sum_all_weights + particles[i].weight;
}
for (int i = 0; i < num_particles; i++)
{
particles[i].weight = particles[i].weight/sum_all_weights;
weights[i] = particles[i].weight;
}
}
void ParticleFilter::resample() {
/**
* TODO: Resample particles with replacement with probability proportional
* to their weight.
* NOTE: You may find std::discrete_distribution helpful here.
* http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
*/
//Variable initialization
std::default_random_engine gen;
vector<Particle> new_set_particles;
std::uniform_int_distribution<int> unif_dist_index(0, num_particles-1);
auto unif_index{unif_dist_index(gen)};
double max_weight{*max_element(weights.begin(), weights.end())};
std::uniform_real_distribution<double> unif_dist_weight(0.0, max_weight);
double beta{0.0};
//Wheel
for (int i = 0; i < num_particles; i++) {
beta = beta + unif_dist_weight(gen) * 2.0;
while (weights[unif_index] < beta) {
beta = beta - weights[unif_index];
unif_index = (unif_index + 1) % num_particles;
}
new_set_particles.push_back(particles[unif_index]);
}
particles = new_set_particles;
}
string ParticleFilter::getAssociations(Particle best) {
vector<int> v = best.associations;
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseCoord(Particle best, string coord) {
vector<double> v;
if (coord == "X") {
v = best.sense_x;
} else {
v = best.sense_y;
}
std::stringstream ss;
copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
|
// Created on: 1995-12-01
// Created by: EXPRESS->CDL V0.2 Translator
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepGeom_Axis2Placement3d_HeaderFile
#define _StepGeom_Axis2Placement3d_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Boolean.hxx>
#include <StepGeom_Placement.hxx>
class StepGeom_Direction;
class TCollection_HAsciiString;
class StepGeom_CartesianPoint;
class StepGeom_Axis2Placement3d;
DEFINE_STANDARD_HANDLE(StepGeom_Axis2Placement3d, StepGeom_Placement)
class StepGeom_Axis2Placement3d : public StepGeom_Placement
{
public:
//! Returns a Axis2Placement3d
Standard_EXPORT StepGeom_Axis2Placement3d();
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Handle(StepGeom_CartesianPoint)& aLocation, const Standard_Boolean hasAaxis, const Handle(StepGeom_Direction)& aAxis, const Standard_Boolean hasArefDirection, const Handle(StepGeom_Direction)& aRefDirection);
Standard_EXPORT void SetAxis (const Handle(StepGeom_Direction)& aAxis);
Standard_EXPORT void UnSetAxis();
Standard_EXPORT Handle(StepGeom_Direction) Axis() const;
Standard_EXPORT Standard_Boolean HasAxis() const;
Standard_EXPORT void SetRefDirection (const Handle(StepGeom_Direction)& aRefDirection);
Standard_EXPORT void UnSetRefDirection();
Standard_EXPORT Handle(StepGeom_Direction) RefDirection() const;
Standard_EXPORT Standard_Boolean HasRefDirection() const;
DEFINE_STANDARD_RTTIEXT(StepGeom_Axis2Placement3d,StepGeom_Placement)
protected:
private:
Handle(StepGeom_Direction) axis;
Handle(StepGeom_Direction) refDirection;
Standard_Boolean hasAxis;
Standard_Boolean hasRefDirection;
};
#endif // _StepGeom_Axis2Placement3d_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef INTERNAL_SPELLCHECK_SUPPORT
#ifndef SPC_USE_HUNSPELL_ENGINE
#include "modules/spellchecker/src/opspellchecker.h"
DictionaryEncoding GetEncodingFromString(UINT8 *enc_str)
{
if (str_eq(enc_str,(UINT8*)"UTF-8"))
return UTF8_ENC;
return BIT8_ENC;
}
FlagEncoding GetFlagEncodingFromString(UINT8 *enc_str)
{
if (str_eq(enc_str,(UINT8*)"long"))
return FLAG_LONG_ENC;
else if (str_eq(enc_str,(UINT8*)"num"))
return FLAG_NUM_ENC;
else if (str_eq(enc_str,(UINT8*)"UTF-8"))
return FLAG_UTF8_ENC;
return FLAG_UNKNOWN_ENC;
}
AffixConditionData *OpSpellChecker::GetAffixConditionData(UINT8 *str, UINT8* buffer, int buf_len, int &cond_count)
{
int str_len = op_strlen((const char*)str);
if (!str_len || (int)(str_len*(sizeof(UINT32)+sizeof(AffixConditionData))) > buf_len)
return NULL;
UINT32 *chars = (UINT32*)(buffer+str_len*sizeof(AffixConditionData));
AffixConditionData *cond_array = (AffixConditionData*)buffer;
cond_count = 0;
while (*str)
{
UINT32 ch;
int len = 0;
AffixConditionData *cond = cond_array + cond_count++;
BOOL negative = FALSE;
if (*str == ']')
return NULL;
if (*str == '^')
{
negative = TRUE;
str++;
if (*str == '^' || *str == ']')
return NULL;
}
if (*str == '[')
{
str++;
if (*str == '^')
{
negative = TRUE;
str++;
}
while (*str && *str != ']') // accept un-terminated ([blabla\0) condition to fix the gsc_FR dictionary
{
SPC_NEXT_CHAR(ch,str);
if (ch == '\0' || ch == '[')
return NULL;
chars[len++] = ch;
}
if (*str)
str++;
if (!len)
return NULL;
}
else
{
SPC_NEXT_CHAR(ch,str);
if (ch == '\0')
return NULL;
len = 1;
*chars = ch;
}
cond->chars = chars;
cond->len = len;
cond->negative = negative;
chars += len;
}
return cond_array;
}
CompoundRuleConditionData *OpSpellChecker::GetCompoundRuleConditionData(UINT8 *str, UINT8* buffer, int buf_len, FlagEncoding flag_encoding, int &cond_count)
{
int str_len = op_strlen((const char*)str);
if (!str_len || (int)(str_len*(sizeof(UINT16)+sizeof(CompoundRuleConditionData))) > buf_len)
return NULL;
UINT16 *indexes = (UINT16*)(buffer+str_len*sizeof(CompoundRuleConditionData));
CompoundRuleConditionData *cond_array = (CompoundRuleConditionData*)buffer;
cond_count = 0;
BOOL num_flg = flag_encoding == FLAG_NUM_ENC;
while (*str)
{
int flag_index;
int len = 0;
int bytes_used = 0;
CompoundRuleConditionData *cond = cond_array + cond_count++;
BOOL negative = FALSE;
if (op_strchr("]*+", *str) || num_flg && *str == ',')
return NULL;
if (*str == '^')
{
negative = TRUE;
str++;
if (!*str || op_strchr("]*+^", *str) || num_flg && *str == ',')
return NULL;
}
if (*str == '[')
{
str++;
if (*str == '^')
{
negative = TRUE;
str++;
}
while (*str != ']')
{
if (!*str || op_strchr("[*+^", *str) || num_flg && *str == ',')
return NULL;
flag_index = decode_flag(str,flag_encoding,bytes_used);
if (flag_index < 0)
return NULL;
str += bytes_used;
if (num_flg && *str == ',')
str++;
indexes[len++] = (UINT16)flag_index;
}
str++;
if (!len)
return NULL;
}
else
{
flag_index = decode_flag(str,flag_encoding,bytes_used);
if (flag_index < 0)
return NULL;
str += bytes_used;
if (num_flg && *str == ',')
str++;
len = 1;
*indexes = flag_index;
}
cond->indexes = indexes;
cond->len = len;
cond->negative = negative;
indexes += len;
cond->multiple_type = 0;
if (*str == '*' || *str == '+')
cond->multiple_type = *(str++);
}
return cond_array;
}
OP_STATUS OpSpellChecker::PostProcessPass(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
if (state->GetPass() == 0)
{
RETURN_IF_ERROR(fd->PostProcessCircumfixes(state));
RETURN_IF_ERROR(fd->ConvertAliasIndexes());
fd->SetTypeIdBits();
RETURN_IF_ERROR(SetupCharConverters());
RETURN_IF_ERROR(CreateUTF16FromBuffer(fd->GetWordChars(), m_word_chars, &m_allocator));
RETURN_IF_ERROR(CreateUTF16FromBuffer(fd->GetBreakChars(), m_break_chars, &m_allocator));
}
else if (state->GetPass() == 1)
{
RETURN_IF_ERROR(fd->PostProcessCircumfixes(state));
}
if ( state->IsLastPass() )
{
UINT32 existing_radix_flags = 0;
int i;
for (i=0;i<SPC_RADIX_FLAGS;i++)
{
if (fd->GetFlagTypeCount((AffixFlagType)i))
existing_radix_flags |= 1<<i;
}
m_has_radix_flags = !!existing_radix_flags;
m_has_compounds = (existing_radix_flags & SPC_RADIX_COMPOUND_FLAGS || m_has_compound_rule_flags) && m_compoundwordmax > 1;
}
return OpStatus::OK;
}
inline OP_STATUS OpSpellChecker::ParseIntValue(int *result, HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
int dummy;
HunspellAffixFileLine *line = state->GetCurrentLine();
if (!line->GetWordCount())
return SPC_ERROR(OpStatus::ERR);
*result = pos_num_to_int(line->WordAt(0),0xFFFF,dummy);
return *result <= 0 ? SPC_ERROR(OpStatus::ERR) : OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseSFX(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseAffix(fd,state,TRUE);
}
OP_STATUS OpSpellChecker::ParsePFX(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseAffix(fd,state,FALSE);
}
OP_STATUS OpSpellChecker::ParsePHONE(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
state->SetDicCharsUsed();
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseKEY(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
state->SetDicCharsUsed();
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseAF(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
HunspellAffixFileLine *line = state->GetCurrentLine();
if (!state->GetAliasesDetected())
{
state->SetAliasesDetected();
return OpStatus::OK;
}
if (!line->GetWordCount())
return SPC_ERROR(OpStatus::ERR);
state->SetFlagsUsed();
UINT8 *str = line->WordAt(0);
int bytes_used = 0;
UINT16 *flags = (UINT16*)fd->Allocator()->Allocate16(SPC_MAX_FLAGS_PER_LINE*sizeof(UINT16));
if (!flags)
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
int i = 0;
int f;
while ((f = decode_flag(str,fd->GetFlagEncoding(),bytes_used)) >= 0 && i < SPC_MAX_FLAGS_PER_LINE)
{
flags[i++] = f;
str += bytes_used;
while (*str == ',')
str++;
}
fd->Allocator()->OnlyUsed(i*sizeof(UINT16));
if (!i)
return SPC_ERROR(OpStatus::ERR);
FlagAlias alias = FlagAlias(flags,i);
RETURN_IF_ERROR(fd->AddAlias(alias));
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseTRY(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseSET(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
HunspellAffixFileLine *line = state->GetCurrentLine();
UINT8 *enc_str = line->WordAt(0);
if (!enc_str)
return OpStatus::OK;
if (state->GetDicCharsUsed() || m_enc_string)
return SPC_ERROR(OpStatus::ERR); // Can't use two different encodings
DictionaryEncoding enc = GetEncodingFromString(enc_str);
if (enc == UNKNOWN_ENC)
return SPC_ERROR(OpStatus::ERR);
m_encoding = enc;
m_8bit_enc = IS_8BIT_ENCODING(enc);
if (!m_8bit_enc)
{
OP_DELETEA(m_existing_chars.linear);
m_existing_chars.utf = UTFMapping<UINT32>::Create();
if (!m_existing_chars.utf)
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
}
RETURN_IF_ERROR(fd->SetDictionaryEncoding(enc));
OP_DELETEA(m_enc_string);
int str_len = op_strlen((const char*)enc_str);
m_enc_string = OP_NEWA(char, str_len+1);
if (!m_enc_string)
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
op_strcpy(m_enc_string, (const char*)enc_str);
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseFLAG(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
HunspellAffixFileLine *line = state->GetCurrentLine();
UINT8 *enc_str = line->WordAt(0);
if (!enc_str)
return OpStatus::OK;
FlagEncoding enc = GetFlagEncodingFromString(enc_str);
if (enc == FLAG_UNKNOWN_ENC || state->GetFlagsUsed() && enc != fd->GetFlagEncoding()) // Can't use different flag encodings...
return SPC_ERROR(OpStatus::ERR);
RETURN_IF_ERROR(fd->SetFlagEncoding(enc));
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCOMPLEXPREFIXES(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDFLAG(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_COMPOUNDFLAG);
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDBEGIN(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_COMPOUNDBEGIN);
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDMIDDLE(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_COMPOUNDMIDDLE);
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDEND(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_COMPOUNDEND);
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDWORDMAX(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
RETURN_IF_ERROR(ParseIntValue(&m_compoundwordmax,fd,state));
m_compoundwordmax = MIN(m_compoundwordmax, SPC_MAX_ALLOWED_COMPOUNDWORDMAX);
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDROOT(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDPERMITFLAG(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_COMPOUNDPERMITFLAG);
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDFORBIDFLAG(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_COMPOUNDFORBIDFLAG);
}
OP_STATUS OpSpellChecker::ParseCHECKCOMPOUNDDUP(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCHECKCOMPOUNDREP(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCHECKCOMPOUNDTRIPLE(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCHECKCOMPOUNDCASE(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
m_checkcompoundcase = TRUE;
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseNOSUGGEST(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_NOSUGGEST);
}
OP_STATUS OpSpellChecker::ParseFORBIDDENWORD(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseLEMMA_PRESENT(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCIRCUMFIX(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
int dummy;
HunspellAffixFileLine *line = state->GetCurrentLine();
if (!line->GetWordCount())
return SPC_ERROR(OpStatus::ERR);
state->SetFlagsUsed();
int flag_index = decode_flag(line->WordAt(0),fd->GetFlagEncoding(),dummy);
if (flag_index < 0)
return SPC_ERROR(OpStatus::ERR);
RETURN_IF_ERROR(fd->AddCircumfixFlagIndex(flag_index));
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseONLYINCOMPOUND(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_ONLYINCOMPOUND);
}
OP_STATUS OpSpellChecker::ParsePSEUDOROOT(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_NEEDAFFIX);
}
OP_STATUS OpSpellChecker::ParseNEEDAFFIX(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_NEEDAFFIX);
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDMIN(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseIntValue(&m_compoundmin,fd,state);
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDSYLLABLE(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseSYLLABLENUM(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCHECKNUM(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseWORDCHARS(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
state->SetDicCharsUsed();
return fd->AddWordChars(state->GetCurrentLine()->WordAt(0));
}
OP_STATUS OpSpellChecker::ParseIGNORE(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCHECKCOMPOUNDPATTERN(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCOMPOUNDRULE(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
if (state->GetPass() == 0)
return ParseCompoundRulePass0(fd,state);
OP_ASSERT(state->GetPass() == 1);
return ParseCompoundRulePass1(fd,state);
}
OP_STATUS OpSpellChecker::ParseCompoundRulePass0(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
int i,j;
HunspellAffixFileLine *line = state->GetCurrentLine();
if (!fd->GetFlagTypeCount(AFFIX_TYPE_COMPOUNDRULEFLAG)) // first COMPOUNDRULE is number of compoundrules
{
fd->IncTypeIdFor(AFFIX_TYPE_COMPOUNDRULEFLAG); // reserve 0 for when there are no compoundrule flag
return OpStatus::OK;
}
state->SetFlagsUsed();
UINT8 *str = line->WordAt(0);
if (!str)
return OpStatus::OK;
int cond_count = 0;
CompoundRuleConditionData *rule_data = GetCompoundRuleConditionData(str,TempBuffer(),SPC_TEMP_BUFFER_BYTES,fd->GetFlagEncoding(),cond_count);
if (!rule_data)
return SPC_ERROR(OpStatus::ERR);
OP_ASSERT(cond_count);
int plus_count = 0;
for (i=0;i<cond_count;i++)
{
if (rule_data[i].multiple_type == '+')
plus_count++;
for (j=0;j<rule_data[i].len;j++)
{
int flag_index = (int)rule_data[i].indexes[j];
FlagClass *flag_class = fd->GetFlagClass(flag_index);
if (!flag_class)
{
flag_class = OP_NEW(FlagClass, (AFFIX_TYPE_COMPOUNDRULEFLAG,flag_index));
if (!flag_class)
return SPC_ERROR(OpStatus::ERR);
RETURN_IF_ERROR(fd->AddFlagClass(flag_class,state));
}
else if (flag_class->GetType() != AFFIX_TYPE_COMPOUNDRULEFLAG)
return SPC_ERROR(OpStatus::ERR);
}
}
ReleaseTempBuffer();
cond_count += plus_count; // a+ == aa*
if (cond_count > SPC_COMPUNDRULE_MAX_CONDITIONS)
return SPC_ERROR(OpStatus::ERR);
state->IterateInNextPass(line);
line->SetParserData((void*)cond_count);
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCompoundRulePass1(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
int i,j;
HunspellAffixFileLine *line = state->GetCurrentLine();
UINT8 *str = line->WordAt(0);
int total_cond_count = (int)(long)line->GetParserData();
CompoundRule *rule = OP_NEW(CompoundRule, ());
if (!rule)
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
if (m_compound_rules.AddElement(rule) < 0)
{
OP_DELETE(rule);
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
}
RETURN_IF_ERROR(rule->Initialize(total_cond_count,fd->GetFlagTypeCount(AFFIX_TYPE_COMPOUNDRULEFLAG),&m_allocator));
int cond_count = 0;
CompoundRuleConditionData *rule_data = GetCompoundRuleConditionData(str,TempBuffer(),SPC_TEMP_BUFFER_BYTES,fd->GetFlagEncoding(),cond_count);
if (!rule_data)
{
OP_ASSERT(!"This should work as it worked in pass 0.");
return SPC_ERROR(OpStatus::ERR);
}
for (i=0;i<cond_count;i++)
{
for (j=0;j<rule_data->len;j++)
{
FlagClass *flag_class = fd->GetFlagClass(rule_data->indexes[j]);
OP_ASSERT(flag_class && flag_class->GetType() == AFFIX_TYPE_COMPOUNDRULEFLAG);
rule_data->indexes[j] = flag_class->GetFlagTypeId();
}
int multiple_type = rule_data->multiple_type;
int loop = multiple_type == '+' ? 2 : 1;
if (multiple_type == '+')
multiple_type = 0;
for (j=0;j<loop;j++)
{
rule->AddCondition(rule_data->indexes,rule_data->len,rule_data->negative,!!multiple_type);
multiple_type = '*';
}
rule_data++;
}
ReleaseTempBuffer();
OP_ASSERT(rule->GetAddedConditionCount() == rule->GetTotalConditionCount());
m_has_compound_rule_flags = TRUE;
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseMAP(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
HunspellAffixFileLine *line = state->GetCurrentLine();
if (!state->GetMapDetected()) // first MAP is number of MAP entries that follows
{
state->SetMapDetected();
return OpStatus::OK;
}
UINT8 *str = line->WordAt(0);
if (!str)
return OpStatus::OK;
state->SetDicCharsUsed();
int str_len = SPC_STRLEN(str);
if (str_len > SPC_MAX_PER_MAPPING)
return SPC_ERROR(OpStatus::ERR);
if (str_len <= 1)
return OpStatus::OK;
int mapping_idx = m_mappings.GetSize();
if (mapping_idx == SPC_MAX_INDEXES)
return SPC_ERROR(OpStatus::ERR);
MapMapping map_mapping;
int i, ch, map_count = 0;
for (i=0;i<str_len;i++)
{
SPC_NEXT_CHAR(ch,str);
if (ch <= 0)
return SPC_ERROR(OpStatus::ERR);
if (!GetCharMapping(ch).IsPointer())
map_count++;
}
str = line->WordAt(0);
if (map_count < 2)
return OpStatus::OK;
UINT32 *map = (UINT32*)m_allocator.Allocate32(sizeof(UINT32)*(map_count)*2); // + additional space for BIG/small chars
UINT32 *freq = (UINT32*)m_allocator.Allocate32(sizeof(UINT32)*(map_count)*2); // + additional space for BIG/small chars
if (!map || !freq)
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
int pos = 0;
for (i=0;i<str_len;i++)
{
SPC_NEXT_CHAR(ch,str);
if (GetCharMapping(ch).IsPointer())
continue;
map[pos] = (UINT32)ch;
RETURN_IF_ERROR(AddToCharMappings(ch,mapping_idx,pos));
pos++;
}
map_mapping.char_count = map_count;
map_mapping.bit_representation = bits_to_represent(map_count-1); // exclude "most frequent char"
map_mapping.chars = map;
map_mapping.frequencies = freq;
if (m_mappings.AddElement(map_mapping) < 0)
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseBREAK(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
state->SetDicCharsUsed();
return fd->AddBreakChars(state->GetCurrentLine()->WordAt(0));
}
OP_STATUS OpSpellChecker::ParseLANG(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseVERSION(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseMAXNGRAMSUGS(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseNOSPLITSUGS(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseSUGSWITHDOTS(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseKEEPCASE(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return ParseFlagGeneral(fd,state,AFFIX_TYPE_KEEPCASE);
}
OP_STATUS OpSpellChecker::ParseSUBSTANDARD(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseCHECKSHARPS(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
m_checksharps = TRUE;
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseAffixPass0(HunspellAffixFileData *fd, HunspellAffixFileParseState *state, BOOL is_suffix)
{
UINT8 *str;
HunspellAffixFileLine *line = state->GetCurrentLine();
if (line->GetWordCount() < 3)
return SPC_ERROR(OpStatus::ERR);
int dummy = 0;
state->SetFlagsUsed();
int flag_index = decode_flag(line->WordAt(0),fd->GetFlagEncoding(),dummy);
if (flag_index < 0)
return SPC_ERROR(OpStatus::ERR); // invalid name
BOOL can_combine = *(line->WordAt(1)) == 'Y';
int rule_count = pos_num_to_int(line->WordAt(2),65000,dummy);
if (rule_count < 0)
return SPC_ERROR(OpStatus::ERR);
if (rule_count == 0)
return OpStatus::OK;
OpSpellCheckerAffix *affix = OP_NEW(OpSpellCheckerAffix, (flag_index,is_suffix,can_combine,rule_count));
if (!affix)
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
RETURN_IF_ERROR(fd->AddFlagClass(affix,state));
line->SetParserData(affix);
state->IterateInNextPass(line);
int actual_rule_count = 0;
int line_index = line->GetLineIndex()+1;
HunspellAffixFileLine *rule_line = fd->LineAt(line_index);
while (rule_line && rule_line->Type() == line->Type() && decode_flag(rule_line->WordAt(0),fd->GetFlagEncoding(),dummy) == flag_index)
{
OpSpellCheckerAffixRule rule;
UINT32 *res = NULL;
actual_rule_count++;
if (rule_line->GetWordCount() < 4)
return SPC_ERROR(OpStatus::ERR);
UINT8 *strip_chars = rule_line->WordAt(1);
UINT8 *affix_chars = rule_line->WordAt(2);
UINT8 *cond_str = rule_line->WordAt(3);
if (*strip_chars != '0')
{
RETURN_IF_ERROR(GetWideStrPtr(strip_chars,res,fd->Allocator()));
rule.SetStripChars(res);
}
str = affix_chars;
BOOL has_affix_chars = *str != '0' && *str != '/';
while (*str && *str != '/')
str++;
if (*str == '/') // there are flags...
{
*str = '\0';
if (str[1])
rule.SetFlags(str+1); // wait with flag-parsing to next pass for the possibility of aliases
}
res = NULL;
if (has_affix_chars)
RETURN_IF_ERROR(GetWideStrPtr(affix_chars,res,fd->Allocator()));
rule.SetAffixChars(res);
RETURN_IF_ERROR(AddExistingCharsAtAffix(rule.GetAffixChars(), rule.GetAffixCharLength()));
if (*cond_str != '.' && has_any_not(cond_str, "[]^")) // there are conditions...
rule.SetConditionString(cond_str);
RETURN_IF_ERROR(affix->AddRule(rule));
rule_line = fd->LineAt(++line_index);
}
state->SetCurrentLine(line_index);
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseAffixPass1(HunspellAffixFileData *fd, HunspellAffixFileParseState *state, BOOL is_suffix)
{
int i,j,k;
OpSpellCheckerAffix *affix = (OpSpellCheckerAffix*)state->GetCurrentLine()->GetParserData();
if (!affix)
return OpStatus::OK; // this affix has been replaced by another one with the same flag-name, hack in order to support error (I guess) in en_GB
int char_count = 1; // zero is the "unknown" character (for chars not present in this affix's condition strings)
int max_cond_len = 0;
for (i=0;i<affix->GetRuleCount();i++) // assign indexes, count condition characters + set flags
{
OpSpellCheckerAffixRule *rule = affix->GetRulePtr(i);
if (rule->GetFlags())
{
UINT16 *flags = NULL;
RETURN_IF_ERROR(GetFlagPtr(rule->GetFlagsUnParsed(), flags, fd, fd->Allocator()));
rule->SetFlags(flags);
}
UINT8 *cond = rule->GetConditionString();
if (!cond)
continue;
int cond_len = 0;
AffixConditionData *cond_data = GetAffixConditionData(cond,TempBuffer(),SPC_TEMP_BUFFER_BYTES,cond_len);
if (!cond_data || cond_len > SPC_MAX_AFFIX_RULE_CONDITION_LENGTH)
return SPC_ERROR(OpStatus::ERR);
for (j=0;j<cond_len;j++)
{
for (k=0;k<cond_data[j].len;k++)
{
int ch = (int)(cond_data[j].chars[k]);
UINT16 *ch_idx = fd->GetCharIndexPtrForAffix(ch,affix);
if (!ch_idx)
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
if (!*ch_idx)
{
*ch_idx = (UINT16)(char_count++);
if (char_count&0x10000)
return SPC_ERROR(OpStatus::ERR); // Too many different chars in the same affix's conditions
}
}
}
ReleaseTempBuffer();
OP_ASSERT(cond_len);
rule->SetConditionLength(cond_len);
max_cond_len = MAX(cond_len,max_cond_len);
}
if (char_count == 1)
char_count = 0; // only unconditional rules in this affix
RETURN_IF_ERROR(affix->SetConditionProperties(max_cond_len,char_count));
for (i=0;i<affix->GetRuleCount();i++)
{
OpSpellCheckerAffixRule *rule = affix->GetRulePtr(i);
UINT8 *cond = rule->GetConditionString();
if (!cond)
continue;
int cond_len = 0;
int str_len = op_strlen((const char*)cond);
int *cond_chars = (int*)TempBuffer();
UINT8 *buffer = (UINT8*)cond_chars; buffer += str_len * sizeof(int); // use TempBuffer for cond_data as well
int buf_size = SPC_TEMP_BUFFER_BYTES - str_len*sizeof(int);
AffixConditionData *cond_data = GetAffixConditionData(cond,buffer,buf_size,cond_len);
if (!cond_data)
return SPC_ERROR(OpStatus::ERR);
OP_ASSERT(cond_len == rule->GetConditionLength());
for (j=0;j<cond_len;j++)
{
int cond_char_count = cond_data[j].len;
for (k=0;k<cond_char_count;k++)
{
cond_chars[k] = fd->GetCharIndexForAffix(cond_data[j].chars[k],affix);
OP_ASSERT(cond_chars[k]);
}
int pos = affix->IsSuffix() ? cond_len - j - 1 : j;
affix->SetRuleConditions(rule,cond_chars,cond_char_count,pos,cond_data[j].negative);
}
ReleaseTempBuffer();
}
return OpStatus::OK;
}
OP_STATUS OpSpellChecker::ParseAffix(HunspellAffixFileData *fd, HunspellAffixFileParseState *state, BOOL is_suffix)
{
state->SetDicCharsUsed();
if (state->GetPass() == 0)
return ParseAffixPass0(fd,state,is_suffix);
if (state->GetPass() == 1)
return ParseAffixPass1(fd,state,is_suffix);
OP_ASSERT(FALSE);
return SPC_ERROR(OpStatus::ERR);
}
OP_STATUS OpSpellChecker::ParseREP(HunspellAffixFileData *fd, HunspellAffixFileParseState *state)
{
HunspellAffixFileLine *line = state->GetCurrentLine();
UINT8 *to_rep = line->WordAt(0);
if (!to_rep)
return OpStatus::OK;
int to_rep_len = SPC_STRLEN(to_rep);
UINT8 *rep = line->WordAt(1);
if (!rep && !m_rep.GetSize() && *to_rep > '0' && *to_rep < '9')
return OpStatus::OK; // this is probably just a number telling how many REP entries there are...
int rep_len = rep ? SPC_STRLEN(rep) : 0;
UINT32 *rep_data = (UINT32*)m_allocator.Allocate32(sizeof(UINT32)*(to_rep_len+rep_len+3));
if (!rep_data)
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
UINT32 *rep_start = rep_data;
*(rep_data++) = to_rep_len;
RETURN_IF_ERROR(GetWideStrPtr(to_rep,rep_data,NULL));
rep_data += to_rep_len;
(*rep_data++) = rep_len;
if (rep_len)
RETURN_IF_ERROR(GetWideStrPtr(rep,rep_data,NULL));
if (m_rep.AddElement(rep_start) < 0)
return SPC_ERROR(OpStatus::ERR_NO_MEMORY);
return OpStatus::OK;
}
#endif
#endif // INTERNAL_SPELLCHECK_SUPPORT
|
#ifndef ANDROIDPERMISSIONS_H
#define ANDROIDPERMISSIONS_H
#include <QObject>
#include <QtAndroid>
class AndroidPermissions : public QObject
{
Q_OBJECT
public:
explicit AndroidPermissions(QObject *parent = nullptr);
// Q_INVOKABLE bool requestAndroidPermissions();
Q_INVOKABLE void requestAndroidPermissions();
signals:
void requestPermissions();
void permissionsAccepted();
void permissionsDenied();
};
#endif // ANDROIDPERMISSIONS_H
|
using namespace std;
class Encryptor{
private:
string cylines; //Cyphered Data
string password; //Password
int N; //Number of Characters Encrypted (Times Looped)
int TAP; //Total ASCII Password
int OAL; //Original ASCII Letter
int ACL; //Algorithm Cyhpered Letter
string flow; //The String in which all the manipulation will be done before writing output to file.
fstream outFile; //Output File;
fstream inFile; //InFile;
bool debug;
void read_Input(char* inFileName);
void password_Displacement();
void casual_Algorithm();
void header_Creation();
void vector_Algorithm();
void output(char* outFileName);
void log(bool loud, string message);
void log(ofstream& fout, string message);
public:
Encryptor();
Encryptor(bool debugParam);
void encrypt(string pass, char* inFileName, char* outFileName, bool RemoveOrigin, bool b64, bool pDisplacement, bool vectorAlgorithm, bool loud,bool header);
void empty();
//string GetRawCypher();
//void empty();
//PrintFlow
//PrintCyLines
//Empty
};
Encryptor::Encryptor(){
//DEFAULT CLASS CONSTRUCTOR//
debug = false;
}
Encryptor::Encryptor(bool debugParam){
//OVERLOADED CLASS CONSTRUCTOR//
debug = debugParam;
log(true,"Debug Mode Activated");
}
void Encryptor::encrypt(string pass, char* inFileName, char* outFileName, bool RemoveOrigin, bool b64, bool pDisplacement,bool vectorAlgorithm, bool loud,bool header){
//Convert Passwords to ASCII
password = pass;
cylines = ""; //Cyphered Data
N = 0; //Number of Character Encrypted (Times looped)
TAP = 0; //Total ASCII Password
OAL = 0; //Original ASCII Letter
ACL = 0; //Algorithm Crypted Letter
flow = ""; //The String in which all the manipulation will be done before writing output to file.
//1. ADD PASSWORD
for(int i = 0; i <(int)password.length(); i++) {
TAP += password[i];
}
///////////////////////////////////
//2. READ FROM FILE -> BUFFER -> STRING.
read_Input(inFileName);
///////////////////////////////////
//3. BASE64 ENCRYPTION //
if (b64 == true){
//cout << "\nOriginal Text: "<<flow<<endl;
flow = base64_encode(reinterpret_cast<const unsigned char*>(flow.c_str()), flow.length());
//cout << "Base64 Encrypted: "<<flow<<endl;
}
/////////////////////////
//4. ANARCHY VECTOR ALGORITHM //
if (vectorAlgorithm){
vector_Algorithm();
}
/////////////////////////
//5. PASSWORD DISPLACEMENT
if (pDisplacement){
password_Displacement();
}
//////////////////////////
//4. CK ENCRYPTION ALGORITHM
// -a. Convert letter to ASCII then sum with TAP;
// -b. Check that it doesn't end up out of range (32-126)
casual_Algorithm();
//6. HEADER
if (header){
header_Creation();
}
///////////////////////////////
//6. OUTPUT TO TEXTFILE
output(outFileName);
//7. Option: Delete Original
if (RemoveOrigin){
if (remove(inFileName) != 0){cout << "Couldn't delete original file";}
}
//ESTO VA A SER ELIMINADO POR EL LOG() FUNCTION.
//8. Option: Loud Printing
//if (loud) {
//cout << "\n\nOriginal Text:\n" << flow1;
//cout << "\n\nEncrypted Text:\n" <<cylines << "\n\n";}
}
void Encryptor::read_Input(char* inFileName){
ifstream inFile(inFileName);
string flow1;
inFile.seekg(0, ios::end);
flow1.reserve(inFile.tellg());
inFile.seekg(0, ios::beg);
flow1.assign((istreambuf_iterator<char>(inFile)),istreambuf_iterator<char>());
//There is a difference between flow and flow1 for debuggin purpose to be able to compare integrity
flow = flow1;
}
void Encryptor::password_Displacement(){
int dispNum = 1+(TAP%(password.length()));
int dispLetter = flow[dispNum] + password[(password.length()-1)];
while (dispLetter > 126) {
dispLetter -=94;
}
flow[dispNum] = dispLetter;
}
void Encryptor::casual_Algorithm(){
for(int i = 0; i <(int)flow.length(); i++) {
OAL = flow[i];
//if (OAL ==10){ACL = 10;} //Backspace - No deberia pasar nada (?)
//if (OAL ==13){ACL = 13;} //Enter
if ((OAL >= 32) && (OAL <=126)) {
ACL = OAL+TAP+N;
N+=1;
while (ACL > 126) {
ACL -=94;
}
}
else {
ACL = OAL; //ACA NUEVO
}
cylines.append(1,(char)ACL);
}
}
void Encryptor::header_Creation(){
srand(time(0));
int bodySize = (1+(rand()%11))+(password.length());
string body = "";
char pointer = password[(TAP % password.length())];
char randLetter =(rand()%33+93);
for (int i = 0; i<=bodySize;i++){
randLetter =((rand()%33)+93);
while (randLetter == pointer){
randLetter=(rand()%33+93);
}
body.append(1,randLetter);
}
body.append(1,pointer);
string HC = "";
HC.append(body);
HC.append(cylines);
cylines = HC;
}
void Encryptor::output(char* outFileName){
outFile.open(outFileName,fstream::out);
outFile << cylines;
outFile.close();
}
void Encryptor::vector_Algorithm(){
//Precalculations
int PocketSize = password.length(); //Each Pocket has this number of characters.
int NumFullPockets = flow.length() / PocketSize; //Number of COMPLETE Pockets.
int LastPocketSize = flow.length() % NumFullPockets; //This is the Size of the last Pocket. (if it is zero then the flow.length is divisible by the password.length
vector<string> cyVector; //Vector that wil be used to store the pockets.
//Forming the Packets inside the Vector
for (int i= 0; i < flow.length(); i+=(PocketSize)){
cyVector.push_back(flow.substr(i,PocketSize));
}
//Enforcing Order (Decryption)
for (int i=0; i<(cyVector.size()-2);i+=2){ //(VectorSize-1 = Final Packet.) -1 Second to last packet
string temp = cyVector[i];
cyVector[i] = cyVector[i+1];
cyVector[i+1] = temp;
}
//Reforming the String
flow = "";
for (int i= 0; i<cyVector.size();i++){
flow.append(cyVector[i]);
}
}
void Encryptor::empty(){
if (outFile.good()){
outFile.close();
}
if (inFile.good()){
inFile.close();
}
}
void Encryptor::log(bool loud, string message){
if (loud){
cout << message << endl;
}
if (debug){
fstream fout("log.txt",fstream::out);
log(fout, message);
fout.close();
}
}
void Encryptor::log(ofstream& fout, string message){
fout << message;
}
|
#include <iberbar/RHI/D3D9/Texture.h>
#include <iberbar/RHI/D3D9/Device.h>
iberbar::RHI::D3D9::CTexture::CTexture( CDevice* pDevice )
: ITexture()
, m_pDevice( pDevice )
, m_pD3DTexture( nullptr )
{
m_pDevice->AddRef();
}
iberbar::RHI::D3D9::CTexture::~CTexture()
{
D3D_SAFE_RELEASE( m_pD3DTexture );
UNKNOWN_SAFE_RELEASE_NULL( m_pDevice );
}
iberbar::CResult iberbar::RHI::D3D9::CTexture::CreateEmpty( int w, int h )
{
HRESULT hRet;
//hRet = m_pDevice->GetD3DDevice()->CreateTexture( w, h, 1, 0, D3DFORMAT::D3DFMT_A8R8G8B8, D3DPOOL::D3DPOOL_MANAGED, &m_pD3DTexture, nullptr );
//if ( FAILED( hRet ) )
//{
// return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
//}
hRet = D3DXCreateTexture( m_pDevice->GetD3DDevice(), w, h, 1, 0, D3DFORMAT::D3DFMT_A8R8G8B8, D3DPOOL::D3DPOOL_MANAGED, &m_pD3DTexture );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
D3DSURFACE_DESC lc_SurfaceDesc;
m_pD3DTexture->GetLevelDesc( 0, &lc_SurfaceDesc );
if ( lc_SurfaceDesc.Format != D3DFMT_A8R8G8B8 )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
m_Size = CSize2i( w, h );
m_bIsManaged = true;
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CTexture::CreateFromFileInMemory( const void* pData, uint32 nDataSize )
{
HRESULT hRet;
D3DXIMAGE_INFO info;
hRet = D3DXGetImageInfoFromFileInMemory( pData, nDataSize, &info );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
//hRet = D3DXCreateTextureFromFileInMemory( m_pDevice->GetD3DDevice(), pData, nDataSize, &m_pD3DTexture );
hRet = D3DXCreateTextureFromFileInMemoryEx(
m_pDevice->GetD3DDevice(),
pData,
nDataSize,
info.Width, info.Height,
D3DFMT_FROM_FILE,
0,
D3DFMT_A8R8G8B8,
D3DPOOL_MANAGED,
D3DX_FILTER_NONE, // NONE真实像素,其他会拉伸,会出现模糊
D3DX_DEFAULT,
0, nullptr, nullptr,
&m_pD3DTexture );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
IDirect3DSurface9* pSurface = nullptr;
hRet = m_pD3DTexture->GetSurfaceLevel( 0, &pSurface );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
D3DSURFACE_DESC SurfaceDesc;
pSurface->GetDesc( &SurfaceDesc );
m_Size = CSize2i( SurfaceDesc.Width, SurfaceDesc.Height );
m_bIsManaged = true;
pSurface->Release();
pSurface = nullptr;
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CTexture::CreateFromFileA( const char* strFile )
{
HRESULT hRet;
D3DXIMAGE_INFO info;
hRet = D3DXGetImageInfoFromFileA( strFile, &info );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
hRet = D3DXCreateTextureFromFileExA(
m_pDevice->GetD3DDevice(),
strFile,
info.Width, info.Height,
D3DFMT_FROM_FILE,
0,
D3DFMT_A8R8G8B8,
D3DPOOL_MANAGED,
D3DX_FILTER_NONE, // NONE真实像素,其他会拉伸,会出现模糊
D3DX_DEFAULT,
0, nullptr, nullptr,
&m_pD3DTexture );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
IDirect3DSurface9* pSurface = nullptr;
hRet = m_pD3DTexture->GetSurfaceLevel( 0, &pSurface );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
D3DSURFACE_DESC SurfaceDesc;
pSurface->GetDesc( &SurfaceDesc );
m_Size = CSize2i( SurfaceDesc.Width, SurfaceDesc.Height );
m_bIsManaged = true;
pSurface->Release();
pSurface = nullptr;
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CTexture::CreateFromFileW( const wchar_t* strFile )
{
HRESULT hRet = D3DXCreateTextureFromFileW( m_pDevice->GetD3DDevice(), strFile, &m_pD3DTexture );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
IDirect3DSurface9* pSurface = nullptr;
hRet = m_pD3DTexture->GetSurfaceLevel( 0, &pSurface );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
D3DSURFACE_DESC SurfaceDesc;
pSurface->GetDesc( &SurfaceDesc );
m_Size = CSize2i( SurfaceDesc.Width, SurfaceDesc.Height );
m_bIsManaged = true;
pSurface->Release();
pSurface = nullptr;
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CTexture::CreateFromPixels( int w, int h, void* pPixels )
{
assert( m_pD3DTexture );
HRESULT hRet;
hRet = D3DXCreateTexture( m_pDevice->GetD3DDevice(), w, h, 0, 0, D3DFORMAT::D3DFMT_A8R8G8B8, D3DPOOL::D3DPOOL_MANAGED, &m_pD3DTexture );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
D3DLOCKED_RECT D3DLockRect;
RECT rect;
rect.left = 0;
rect.top = 0;
rect.right = w;
rect.bottom = h;
hRet = m_pD3DTexture->LockRect( 0, &D3DLockRect, &rect, 0 );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
uint32 nByteCount = w * h * 4;
memcpy_s( D3DLockRect.pBits, nByteCount, pPixels, nByteCount );
m_pD3DTexture->UnlockRect( 0 );
m_Size = CSize2i( w, h );
m_bIsManaged = true;
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CTexture::SetPixels( const void* pPixels, int nx, int ny, int nw, int nh )
{
assert( (nx + nw) <= m_Size.w );
assert( (ny + nh) <= m_Size.h );
HRESULT hRet;
D3DLOCKED_RECT D3DLockRect;
RECT rect;
rect.left = nx;
rect.top = ny;
rect.right = nx + nw;
rect.bottom = ny + nh;
hRet = m_pD3DTexture->LockRect( 0, &D3DLockRect, &rect, 0 );
if ( FAILED( hRet ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
}
//
int nCopyPerRow = nw * 4;
uint8* pLockBits = (uint8*)D3DLockRect.pBits;
const uint8* pPixelsTemp = (const uint8*)pPixels;
int nLockedStride = D3DLockRect.Pitch;
int nPixelsStride = nw * 4;
for ( int i = 0; i < nh; i++ )
{
memcpy_s( pLockBits, nPixelsStride, pPixelsTemp, nPixelsStride );
pLockBits += nLockedStride;
pPixelsTemp += nPixelsStride;
}
m_pD3DTexture->UnlockRect( 0 );
//hRet = D3DXFilterTexture( m_pD3DTexture, 0, 0, D3DX_DEFAULT );
//if ( FAILED( hRet ) )
//{
// return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hRet ) );
//}
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CTexture::SaveToFileA( const char* strFile )
{
HRESULT hResult = D3DXSaveTextureToFileA( strFile, D3DXIFF_PNG, m_pD3DTexture, nullptr );
if ( FAILED( hResult ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hResult ) );
}
return CResult();
}
iberbar::CResult iberbar::RHI::D3D9::CTexture::SaveToFileW( const wchar_t* strFile )
{
HRESULT hResult = D3DXSaveTextureToFileW( strFile, D3DXIFF_PNG, m_pD3DTexture, nullptr );
if ( FAILED( hResult ) )
{
return MakeResult( ResultCode::Bad, DXGetErrorDescriptionA( hResult ) );
}
return CResult();
}
|
#include "filtreEnter.h"
FiltreEnter::FiltreEnter()
{
}
FiltreEnter::~FiltreEnter()
{
}
bool FiltreEnter::eventFilter( QObject * inObj, QEvent * inEvent )
{
if ( inEvent->type() == QEvent::KeyPress )
{
QKeyEvent * keyEvent = static_cast<QKeyEvent *>( inEvent );
if ( keyEvent->key() == Qt::Key_Return )
{
emit enter();
return true;
}
if ( keyEvent->key() == Qt::Key_Up )
{
emit up();
return true;
}
if ( keyEvent->key() == Qt::Key_Down )
{
emit down();
return true;
}
if ( keyEvent->key() == Qt::Key_Left )
{
emit left();
return true;
}
if ( keyEvent->key() == Qt::Key_Right )
{
emit right();
return true;
}
}
return QObject::eventFilter( inObj, inEvent );
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <folly/io/SocketOptionMap.h>
#include <folly/net/NetOps.h>
#include <quic/common/QuicAsyncUDPSocketWrapper.h>
namespace quic {
bool isNetworkUnreachable(int err);
void applySocketOptions(
QuicAsyncUDPSocketType& sock,
const folly::SocketOptionMap& options,
sa_family_t family,
folly::SocketOptionKey::ApplyPos pos) noexcept;
} // namespace quic
|
#ifndef GRAPHICS_H
#define GRAPHICS_H
namespace gg
{
class Graphics
{
public:
Graphics(int width, int height);
~Graphics();
void clear(float r, float g, float b) const;
static int screenWidth;
static int screenHeight;
static float aspectRatio;
private:
void init();
};
}
#endif
|
/*=================================================================================================
Author: Renato Farias (renatomdf@gmail.com)
Created on: April 13th, 2012
Updated on: June 12th, 2012
About: This is a simple CPU implementation of the Jump Flooding algorithm from the paper "Jump
Flooding in GPU With Applications to Voronoi Diagram and Distance Transform" [Rong 2006]. The
result is a Voronoi diagram generated from a number of seeds which the user provides with mouse
clicks. You can also click on and drag around a seed to reposition it, if that's your thing.
=================================================================================================*/
#ifndef __JFA_H__
#define __JFA_H__
/*=================================================================================================
INCLUDES
=================================================================================================*/
#include "ImgLib.h"
#include "edlines.h"
#include <vector>
#include <fstream>
#include <unordered_map>
typedef vector<Pixel> EdgeChain;
//typedef vector<vector<Pixel> > VecEdgeChains;
typedef unordered_multimap<int, int> VoiPixelMap;
//namespace JFA {
//
// //这里因为命名相同无法编译通过的原因,简单通过设置命名空间来解决,后续需要完善
//
// //using namespace std;
// typedef struct Pixel {
// int x, y;
//
// Pixel(int tx, int ty) {
// x = tx;
// y = ty;
// }
// Pixel() {};
// } Pixel;
//
// typedef std::vector<Pixel> EdgeChain;
//}
// Represents a Pixel with (x,y) coordinates
/*=================================================================================================
FUNCTIONS
=================================================================================================*/
//void ExecuteJumpFlooding(vector<Pixel> Seeds);
void ExecuteJumpFloodingDis(int* disMap, EdgeChain Seeds, unsigned int xsize, unsigned int ysize);
void ExecuteJumpFloodingVoi(VoiPixelMap &VoiMap, const EdgeChain Seeds, unsigned int xsize, unsigned int ysize);
//EdgeChain VertexOptimization(const EdgeChain constrainedPoints, const EdgeChain cvtSeeds,
// unsigned int xsize, unsigned int ysize, int optTimes, int* distMap);
EdgeChains VertexOptimization(const EdgeChains constrainedPoints, const EdgeChains cvtSeeds,
unsigned int xsize, unsigned int ysize, int optTimes, int* distMap);
#endif
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
char s[111];
bool palindr(const string& s) {
int l = s.length();
for (int i = 0; i + i < l; ++i) {
if (s[i] != s[l - i - 1])
return false;
}
return true;
}
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
vector< pair<int, string> > all[1024];
for (int i = 0; i < 255; ++i)
for (int j = 0; j < 255; ++j) {
int l = sprintf(s, "%u%u", i, j);
int msk = 0;
for (int k = 0; k < l; ++k) msk |= (1 << (s[k] - '0'));
all[msk].push_back(make_pair(i * 256 + j, s));
}
int n;
cin >> n;
int mask = 0;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
mask |= (1 << x);
}
// for (int mask = 1; mask < 1024; ++mask) {
vector< pair<int, int> > ans;
for (int sm = mask; sm > 0; sm = (sm - 1) & mask)
for (int i = 0; i < all[sm].size(); ++i)
for (int sm2 = sm; sm2 > 0; sm2 = (sm2 - 1) & sm) {
int sm3 = (mask ^ sm) | sm2;
for (int j = 0; j < all[sm3].size(); ++j) {
if (palindr(all[sm][i].second + all[sm3][j].second)) {
ans.push_back(make_pair(all[sm][i].first, all[sm3][i].first));
}
}
}
cout << ans.size() << endl;
for (int i =0; i < ans.size(); ++i) {
cout << (ans[i].first >>8) << "." << (ans[i].first & 255) << "."
<< (ans[i].second >> 8) << "." << (ans[i].first & 255) << endl;
}
// }
cerr << clock() << endl;
return 0;
}
|
#pragma once
#include <string>
#include "Inconstructible.h"
#include "Vector.h"
#include "VirtualMethod.h"
#include "WeaponInfo.h"
struct ClientClass;
class Matrix3x4;
enum class WeaponId : short;
enum class WeaponType;
class Collideable {
public:
INCONSTRUCTIBLE(Collideable)
VIRTUAL_METHOD(const Vector&, obbMins, 1, (), (this))
VIRTUAL_METHOD(const Vector&, obbMaxs, 2, (), (this))
};
struct Model {
void* handle;
char name[260];
int loadFlags;
int serverCount;
int type;
int flags;
Vector mins, maxs;
};
#define PROP(func_name, offset, type) \
[[nodiscard]] std::add_lvalue_reference_t<std::add_const_t<type>> func_name() noexcept \
{ \
return *reinterpret_cast<std::add_pointer_t<type>>(this + offset); \
}
enum class ObsMode {
None = 0,
Deathcam,
Freezecam,
Fixed,
InEye,
Chase,
Roaming
};
enum class Team {
None = 0,
Spectators,
TT,
CT
};
constexpr auto EF_NODRAW = 0x20;
class CSPlayer;
class Entity {
public:
INCONSTRUCTIBLE(Entity)
VIRTUAL_METHOD(ClientClass*, getClientClass, 2, (), (this + sizeof(uintptr_t) * 2))
VIRTUAL_METHOD(bool, isDormant, 9, (), (this + sizeof(uintptr_t) * 2))
VIRTUAL_METHOD(int, index, 10, (), (this + sizeof(uintptr_t) * 2))
VIRTUAL_METHOD(const Model*, getModel, 8, (), (this + sizeof(uintptr_t)))
VIRTUAL_METHOD(bool, setupBones, 13, (Matrix3x4* out, int maxBones, int boneMask, float currentTime), (this + sizeof(uintptr_t), out, maxBones, boneMask, currentTime))
VIRTUAL_METHOD(const Matrix3x4&, toWorldTransform, 32, (), (this + sizeof(uintptr_t)))
VIRTUAL_METHOD_V(int&, handle, 2, (), (this))
VIRTUAL_METHOD_V(Collideable*, getCollideable, 3, (), (this))
VIRTUAL_METHOD(Vector&, getAbsOrigin, WIN32_UNIX(10, 12), (), (this))
VIRTUAL_METHOD(Team, getTeamNumber, WIN32_UNIX(88, 128), (), (this))
VIRTUAL_METHOD(int, getHealth, WIN32_UNIX(122, 167), (), (this))
VIRTUAL_METHOD(bool, isAlive, WIN32_UNIX(156, 208), (), (this))
VIRTUAL_METHOD(bool, isPlayer, WIN32_UNIX(158, 210), (), (this))
VIRTUAL_METHOD(bool, isWeapon, WIN32_UNIX(166, 218), (), (this))
VIRTUAL_METHOD(WeaponType, getWeaponType, WIN32_UNIX(455, 523), (), (this))
VIRTUAL_METHOD(WeaponInfo*, getWeaponInfo, WIN32_UNIX(461, 529), (), (this))
static CSPlayer* asPlayer(Entity* entity) noexcept
{
if (entity && entity->isPlayer())
return reinterpret_cast<CSPlayer*>(entity);
return nullptr;
}
auto isSniperRifle() noexcept
{
return getWeaponType() == WeaponType::SniperRifle;
}
auto isEffectActive(int effect) noexcept
{
return (effectFlags() & effect) != 0;
}
PROP(effectFlags, WIN32_UNIX(0xF0, 0x128), int)
PROP(hitboxSet, WIN32_UNIX(0x9FC, 0xFA8), int) // CBaseAnimating->m_nHitboxSet
PROP(weaponId, WIN32_UNIX(0x2FBA, 0x37BA), WeaponId) // CBaseAttributableItem->m_iItemDefinitionIndex
PROP(clip, WIN32_UNIX(0x3274, 0x3AEC), int) // CBaseCombatWeapon->m_iClip1
PROP(isInReload, WIN32_UNIX(0x32B5, 0x3B31), bool) // CBaseCombatWeapon->m_bInReload (client-side only)
PROP(reserveAmmoCount, WIN32_UNIX(0x327C, 0x3AF4), int) // CBaseCombatWeapon->m_iPrimaryReserveAmmoCount
PROP(nextPrimaryAttack, WIN32_UNIX(0x3248, 0x3AC0), float) // CBaseCombatWeapon->m_flNextPrimaryAttack
PROP(prevOwner, WIN32_UNIX(0x3394, 0x3C24), int) // CWeaponCSBase->m_hPrevOwner
PROP(ownerEntity, WIN32_UNIX(0x14C, 0x184), int) // CBaseEntity->m_hOwnerEntity
PROP(spotted, WIN32_UNIX(0x93D, 0xECD), bool) // CBaseEntity->m_bSpotted
PROP(thrower, WIN32_UNIX(0x29B0, 0x3048), int) // CBaseGrenade->m_hThrower
PROP(fireXDelta, WIN32_UNIX(0x9E4, 0xF80), int[100]) // CInferno->m_fireXDelta
PROP(fireYDelta, WIN32_UNIX(0xB74, 0x1110), int[100]) // CInferno->m_fireYDelta
PROP(fireZDelta, WIN32_UNIX(0xD04, 0x12A0), int[100]) // CInferno->m_fireZDelta
PROP(fireIsBurning, WIN32_UNIX(0xE94, 0x1430), bool[100]) // CInferno->m_bFireIsBurning
PROP(fireCount, WIN32_UNIX(0x13A8, 0x1944), int) // CInferno->m_fireCount
PROP(mapHasBombTarget, WIN32_UNIX(0x71, 0x89), bool) // CCSGameRulesProxy->m_bMapHasBombTarget
};
class CSPlayer : public Entity {
public:
VIRTUAL_METHOD(Entity*, getActiveWeapon, WIN32_UNIX(268, 331), (), (this))
VIRTUAL_METHOD(ObsMode, getObserverMode, WIN32_UNIX(294, 357), (), (this))
VIRTUAL_METHOD(Entity*, getObserverTarget, WIN32_UNIX(295, 358), (), (this))
#if IS_WIN32()
auto getEyePosition() noexcept
{
Vector v;
VirtualMethod::call<void, 285>(this, std::ref(v));
return v;
}
auto getAimPunch() noexcept
{
Vector v;
VirtualMethod::call<void, 346>(this, std::ref(v));
return v;
}
#else
VIRTUAL_METHOD(Vector, getEyePosition, 348, (), (this))
VIRTUAL_METHOD(Vector, getAimPunch, 409, (), (this))
#endif
bool canSee(Entity* other, const Vector& pos) noexcept;
bool visibleTo(CSPlayer* other) noexcept;
[[nodiscard]] std::string getPlayerName() noexcept;
void getPlayerName(char(&out)[128]) noexcept;
int getUserId() noexcept;
bool isEnemy() noexcept;
bool isGOTV() noexcept;
std::uint64_t getSteamID() noexcept;
PROP(fov, WIN32_UNIX(0x31F4, 0x39B0), int) // CBasePlayer->m_iFOV
PROP(fovStart, WIN32_UNIX(0x31F8, 0x39B4), int) // CBasePlayer->m_iFOVStart
PROP(defaultFov, WIN32_UNIX(0x333C, 0x3B1C), int) // CBasePlayer->m_iDefaultFOV
PROP(lastPlaceName, WIN32_UNIX(0x35C4, 0x3DF8), char[18]) // CBasePlayer->m_szLastPlaceName
PROP(isScoped, WIN32_UNIX(0x9974, 0xA268), bool) // CCSPlayer->m_bIsScoped
PROP(gunGameImmunity, WIN32_UNIX(0x9990, 0xA284), bool) // CCSPlayer->m_bGunGameImmunity
PROP(flashDuration, WIN32_UNIX(0x1046C, 0x10D8C) - 0x8, float) // CCSPlayer->m_flFlashMaxAlpha - 0x8
PROP(shotsFired, WIN32_UNIX(0x103E0, 0x10D00), int) // CCSPlayer->m_iShotsFired
PROP(money, WIN32_UNIX(0x117B8, 0x120EC), int) // CCSPlayer->m_iAccount
};
class PlantedC4 : public Entity {
public:
INCONSTRUCTIBLE(PlantedC4)
PROP(ticking, WIN32_UNIX(0x2990, 0x3020), bool) // CPlantedC4->m_bBombTicking
PROP(bombSite, WIN32_UNIX(0x2994, 0x3024), int) // CPlantedC4->m_nBombSite
PROP(blowTime, WIN32_UNIX(0x29A0, 0x3030), float) // CPlantedC4->m_flC4Blow
PROP(timerLength, WIN32_UNIX(0x29A4, 0x3034), float) // CPlantedC4->m_flTimerLength
PROP(defuseLength, WIN32_UNIX(0x29B8, 0x3048), float) // CPlantedC4->m_flDefuseLength
PROP(defuseCountDown, WIN32_UNIX(0x29BC, 0x304C), float) // CPlantedC4->m_flDefuseCountDown
PROP(bombDefuser, WIN32_UNIX(0x29C4, 0x3054), int) // CPlantedC4->m_hBombDefuser
};
|
#include <random>
#include <vector>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
constexpr int N_repeat = 100000;
constexpr int N_play_max = 10000;
ofstream file("count.txt");
if (!file.is_open())
{
cout << "open file failed" << endl;
return -1;
}
for (int i = 1; i <= N_play_max; i++)
{
int n_loose = 0;
double loose_pr;
for (int j = 1; j <= N_repeat; j++)
{
int money_now = 1;
for (int play_id = 1; play_id <= i; play_id++)
{
bool win = rand() % 2;
if (win)
{
money_now++;
}
else
{
money_now--;
if (money_now < 0)
{
n_loose++;
break;
}
}
}
}
loose_pr = n_loose / (double)N_repeat;
file << loose_pr << endl;
cout << "i: " << i << "pr=" << loose_pr << endl;
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int random_number()
{
return rand()%100+1;
}
int people_guess(int x)
{
int n;
cout<<"Enter your number: ";
cin>>n;
if(n<x)
{
cout<<"Your number is small"<<endl;
}
else if(n>x)
{
cout<<"Your number is big"<<endl;
}
else cout<<"You win"<<endl;
return n;
}
void play_GuessIt()
{
char t;
do
{
int x,a;
int times=0,point=10000,number=100;
srand(time(0));
x=random_number();
do
{
a=people_guess(x);
times++;
}
while(a!=x);
for(int i=0; i<times-1; i++)
{
point-=2*number;
number--;
}
cout<<"Number of guesses is: "<<times<<endl;
cout<<"The point is: "<<100-times+1<<"/100 and "<<point<<"/10000"<<endl;
cout<<"Enter "<<'"'<<"y"<<'"'<<" to continue, enter a character that does not match "<<'"'<<"y"<<'"'<<" to stop: ";
cin>>t;
}
while(t=='y');
}
int main()
{
play_GuessIt();
}
|
#include <bits/stdc++.h>
using namespace std;
bool op(char c);
int result(int a, int b, char c);
int main()
{
stack<int>pilha;
stack<char>opera;
int ret, cont, ff;
string s;
while(getline(cin, s))
{
cont = ff = ret = 0;
for(int i=0;i<s.size();i++)
{
if(s[i]!=' ')
{
if(op(s[i]))
opera.push(s[i]), cont = 0;
else
{
pilha.push(s[i]-'0'), cont++;
if(i==0 && s.size()>=3)
{
printf("Invalid expression.\n"); ff = 1; break;
}
}
if(cont==2)
{
int a, b; char o;
b = pilha.top(); pilha.pop();
a = pilha.top(); pilha.pop();
if(opera.empty())
{
printf("Invalid expression.\n"); ff = 1; break;
}
o = opera.top(); opera.pop();
ret = result(a, b, o);
if(ret==1<<30)
{
printf("Division by zero.\n"); ff = 1; break;
}
pilha.push(ret); cont = 1;
}
if(cont>2)
{
printf("Invalid expression.\n"); ff = 1; break;
}
}
}
if(ff==0)
{
while(pilha.size()>1)
{
int a, b; char o;
b = pilha.top(); pilha.pop();
a = pilha.top(); pilha.pop();
if(opera.empty())
break;
o = opera.top(); opera.pop();
ret = result(a, b, o);
if(ret==1<<30)
{
printf("Division by zero.\n"); break;
}
pilha.push(ret);
}
if(pilha.empty() || pilha.size()>=2 || opera.size()>=1)
printf("Invalid expression.\n");
else
printf("The answer is %d.\n", pilha.top());
}
while(!pilha.empty())
pilha.pop();
while(!opera.empty())
opera.pop();
}
return 0;
}
int result(int a, int b, char c)
{
if(c=='+')
return b+a;
else if(c=='-')
return b-a;
else if(c=='*')
return b*a;
else
{
if(a==0)
return 1<<30;
return b/a;
}
}
bool op(char c)
{
if(c=='+' || c=='-' || c=='/' || c=='*')
return 1;
else
return 0;
}
|
/*
Copyright (c) 2016, Los Alamos National Security, LLC
All rights reserved.
Copyright 2016. Los Alamos National Security, LLC. This software was produced under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National Laboratory (LANL), which is operated by Los Alamos National Security, LLC for the U.S. Department of Energy. The U.S. Government has rights to use, reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL.
Additionally, redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of Los Alamos National Security, LLC, Los Alamos National Laboratory, LANL, the U.S. Government, 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 MDEngine_h
#define MDEngine_h
#include "AbstractEngine.hpp"
#include "SystemModifier.hpp"
#include "Task.hpp"
#include "Log.hpp"
#include "Graph.hpp"
#include "TransitionFilter.hpp"
#include <map>
#include <string>
#include <boost/optional.hpp>
#include <boost/functional/hash/hash.hpp>
/*
MDTaskMapper class for MDEngine inherited from AbstractTaskMapper
*/
class MDTaskMapper : public AbstractTaskMapper {
public:
MDTaskMapper() : AbstractTaskMapper() {
// worried about clash with data....
AbstractTaskMapper::insert("TASK_MD");
AbstractTaskMapper::insert("TASK_MIN");
AbstractTaskMapper::insert("TASK_SEGMENT");
AbstractTaskMapper::insert("TASK_FORCES");
AbstractTaskMapper::insert("TASK_CARVE_COMPUTE");
AbstractTaskMapper::insert("TASK_CARVE");
AbstractTaskMapper::insert("TASK_SYMMETRY");
AbstractTaskMapper::insert("TASK_INIT_FROM_FILE");
AbstractTaskMapper::insert("TASK_WRITE_TO_FILE");
AbstractTaskMapper::insert("TASK_LABEL");
AbstractTaskMapper::insert("TASK_REMAP");
AbstractTaskMapper::insert("TASK_INIT_VELOCITIES");
AbstractTaskMapper::insert("TASK_INIT_MIN");
AbstractTaskMapper::insert("TASK_MODIFY");
AbstractTaskMapper::insert("TASK_FILTER_TRANSITION");
};
};
/*
MDEngine class inherited from AbstractEngine
*/
template <class System, class EngineTaskMapper>
class MDEngine : public AbstractEngine<EngineTaskMapper> {
public:
typedef AbstractEngine<EngineTaskMapper> BaseEngine;
MDEngine(boost::property_tree::ptree &config, MPI_Comm localComm_, int seed_) : BaseEngine(config,localComm_,seed_) {
seed=seed_;
//move this to the tasks
std::string labelerType=config.get<std::string>("Configuration.StateLabeler.Type", "");
boost::trim(labelerType);
labeler=labelerFactory.at(labelerType)();
labeler->initialize(config);
std::string modifierType=config.get<std::string>("Configuration.SystemModifier.Type", "");
boost::trim(modifierType);
modifier=modifierFactory.at(modifierType)();
modifier->initialize(config);
defaultFlavor=config.get<int>("Configuration.TaskParameters.DefaultFlavor", 0);
BOOST_FOREACH(boost::property_tree::ptree::value_type &v, config.get_child("Configuration.TaskParameters")) {
boost::optional<std::string> otype= v.second.get_optional<std::string>("Task");
if(otype) {
std::string stype=*otype;
boost::trim(stype);
int type=BaseEngine::mapper.type(stype);
int flavor=v.second.get<int>("Flavor");
BOOST_FOREACH(boost::property_tree::ptree::value_type &vv, v.second.get_child("")) {
std::string key=vv.first;
std::string data=vv.second.data();
boost::trim(key);
boost::trim(data);
taskParameters[std::make_pair(type,flavor)][key]=data;
}
}
}
// Assign implementations to dispatchor
// Any overwritten functions must be reassigned here as well
BaseEngine::impls["TASK_MD"] = MDEngine::md_impl; // insert("TASK_MD");
BaseEngine::impls["TASK_MIN"] = MDEngine::min_impl; // insert("TASK_MIN");
BaseEngine::impls["TASK_SEGMENT"] = MDEngine::segment_impl; // insert("TASK_SEGMENT");
BaseEngine::impls["TASK_FORCES"] = MDEngine::forces_impl; // insert("TASK_FORCES");
BaseEngine::impls["TASK_CARVE_COMPUTE"] = MDEngine::carve_compute_impl; // insert("TASK_CARVE_COMPUTE");
BaseEngine::impls["TASK_CARVE"] = MDEngine::carve_impl; // insert("TASK_CARVE");
BaseEngine::impls["TASK_SYMMETRY"] = MDEngine::symmetry_impl; // insert("TASK_SYMMETRY");
BaseEngine::impls["TASK_INIT_FROM_FILE"] = MDEngine::file_init_impl; // insert("TASK_INIT_FROM_FILE");
BaseEngine::impls["TASK_WRITE_TO_FILE"] = MDEngine::file_write_impl; // insert("TASK_WRITE_TO_FILE");
BaseEngine::impls["TASK_LABEL"] = MDEngine::label_impl; // insert("TASK_LABEL");
BaseEngine::impls["TASK_REMAP"] = MDEngine::remap_impl; // insert("TASK_REMAP");
BaseEngine::impls["TASK_INIT_VELOCITIES"] = MDEngine::init_velocities_impl; // insert("TASK_INIT_VELOCITIES");
BaseEngine::impls["TASK_INIT_MIN"] = MDEngine::init_min_impl; // insert("TASK_INIT_MIN");
BaseEngine::impls["TASK_MODIFY"] = MDEngine::modify_impl; // insert("TASK_MODIFY");
BaseEngine::impls["TASK_FILTER_TRANSITION"] = MDEngine::filter_transition_impl; // insert("TASK_FILTER_TRANSITION");
};
int defaultFlavor;
//std::map< std::pair<int,int>, std::map<std::string,std::string> > taskParameters;
std::unordered_map< std::pair<int,int>, std::unordered_map<std::string,std::string>, boost::hash< std::pair<int,int> > > taskParameters;
protected:
std::shared_ptr<AbstractStateLabeler> labeler;
private:
int seed;
std::shared_ptr<AbstractSystemModifier> modifier;
std::function<void(GenericTask&)> md_impl = [this](GenericTask &task) {
/* to be overwritten (in impls as well) */
};
std::function<void(GenericTask&)> min_impl = [this](GenericTask &task) {
/* to be overwritten (in impls as well) */
};
std::function<void(GenericTask&)> init_velocities_impl = [this](GenericTask &task) {
/* to be overwritten (in impls as well) */
};
std::function<void(GenericTask&)> forces_impl = [this](GenericTask &task) {
/* to be overwritten (in impls as well) */
};
std::function<void(GenericTask&)> carve_compute_impl = [this](GenericTask &task) {
/* to be overwritten (in impls as well) */
};
std::function<void(GenericTask&)> symmetry_impl = [this](GenericTask &task) {
/*
clabels match by definition
- find SelfSymmetries of targetInitial: SSI
- find SelfSymmetries of targetFinal: SSF
- find transformation targetInitial -> candidateInitial: TI
- find transformation targetFinal -> candidateFinal: TF
- if TI*SSI == TF*SSF for some members of SSI,SSF, we have a match
- if clabels match across transition, find transformation initial->final
*/
std::unordered_map<std::string,std::string> parameters=\
extractParameters(task.type,task.flavor,defaultFlavor,taskParameters);
//read parameters from the task
bool self_check=safe_extractor<bool>(parameters,"SelfCheck",true);
bool thresh_check=safe_extractor<bool>(parameters,"ThreshCheck",true);
bool vf2_check=safe_extractor<bool>(parameters,"UseVF2",false);
std::set<PointShiftSymmetry> self_symmetry, ops, f_ops;
std::map<Label,std::set<PointShiftSymmetry>> self_symmetries;//,local_self_symmetries;
std::map<int,int> c_map;
Label c_lab,lab;
bool cover;
Transition transition_label;
TransitionSymmetry trans;
System carved;
std::array<double,NDIM> shift;
std::list<System> targets,candidates;
extract("SelfSymmetries",task.arguments,self_symmetries);
extract("Candidates",task.inputData,candidates);
extract("Targets",task.inputData,targets);
Cell bc = targets.begin()->getCell();
// put everything in the basis of the first state? should be done beforehand??
// first off, check for self symmetries (only required for first pair)
if(self_check) {
for(auto &target: targets) {
c_lab = labeler->hash(target,true);
if(self_symmetries.find(c_lab)==self_symmetries.end()) {
LOGGER("MDEngine::symmetry_impl: Self isomorphism search for "<<c_lab)
if(thresh_check) {
LOGGER("MDEngine::symmetry_impl: Carving out defective region")
GenericTask t; t.clear();
t.type=BaseEngine::mapper.type("TASK_CARVE");
insert("State",t.inputData,target);
BaseEngine::process(t);
extract("ThreshState",t.outputData,carved);
if(vf2_check) cover = SelfSymmetriesVF2(carved,self_symmetry);
else cover = SelfSymmetriesDirect(carved,self_symmetry);
} else {
LOGGER("MDEngine::symmetry_impl: No carving for symmetry analysis")
if(vf2_check) cover = SelfSymmetriesVF2(target,self_symmetry);
else cover = SelfSymmetriesDirect(target,self_symmetry);
}
LOGGER("Found "<<self_symmetry.size()<<" symmetries. Covering set: "<<cover)
for(auto &ss : self_symmetry) LOGGER(ss.info_str())
// add to
self_symmetries[c_lab] = self_symmetry;
}
}
} else {
LOGGER("MDEngine::symmetry_impl: OMITTING self isomorphism search for "<<c_lab)
// add identity just in case...
PointShiftSymmetry null;
self_symmetry.insert(null);
if(self_symmetries.find(c_lab)==self_symmetries.end()) {
self_symmetries[c_lab] = self_symmetry;
} else {
self_symmetries[c_lab].insert(null);
}
}
insert("SelfSymmetries",task.returns,self_symmetries);
if(targets.size()<2) return;
auto itts = targets.begin();
auto ittl = task.inputData.equal_range("Targets").first;
LabelPair t_i_l = std::make_pair(ittl->second.canonical_label,ittl->second.label);
LabelPair t_f_l = std::make_pair(std::next(ittl)->second.canonical_label,std::next(ittl)->second.label);
LOGGER("Looking for isomorphisms to I->F == ("<<t_i_l.first<<","<<t_i_l.second<<") -> ("<<t_f_l.first<<","<<t_f_l.second<<")")
// first, check for self transition
double self_shift_mag=0.0,shift_mag=0.0;
transition_label.first = t_i_l;
transition_label.second = t_f_l;
if (t_i_l.first == t_f_l.first) { // i.e. same canonical label
LOGGER("Checking for self transform...")
labeler->isomorphicMap(*itts,*std::next(itts),c_map); // 2 -> C -> 1
ops = find_transforms(*itts,*std::next(itts),c_map);
if(ops.size()>0) {
auto _op = ops.begin();
LOGGER("Found!\n"<<(*_op).info_str())
trans = std::make_pair(transition_label,*_op);
for(int ix=0;ix<NDIM;ix++) self_shift_mag += (_op->shift[ix]) * (_op->shift[ix]);
self_shift_mag = sqrt(self_shift_mag);
insert("SelfTransitions",task.returns,trans);
}
}
if(candidates.size()==0) return;
// now go through candidate list
auto itcs = candidates.begin();
auto itcl = task.inputData.equal_range("Candidates").first;
int ccount=2;
while (itcl!=task.inputData.equal_range("Candidates").second) {
LabelPair c_i_l = std::make_pair(itcl->second.canonical_label,itcl->second.label); // candidate I
LabelPair c_f_l = std::make_pair(std::next(itcl)->second.canonical_label,std::next(itcl)->second.label); // candidate F
LOGGER("Target I->F == ("<<t_i_l.first<<","<<t_i_l.second<<") -> ("<<t_f_l.first<<","<<t_f_l.second<<")")
LOGGER("Candidate I"<<ccount<<"->F"<<ccount<<" == ("<<c_i_l.first<<","<<c_i_l.second<<") -> ("<<c_f_l.first<<","<<c_f_l.second<<")")
if ((c_i_l.first==t_i_l.first) && (c_f_l.first == t_f_l.first)) { // this is just a check, order should be done beforehand...
double cand_shift_mag=0.0;
if ((c_i_l.first==c_f_l.first) && (t_i_l.first==t_f_l.first)) {
// find candidate self transform also
LOGGER("Checking for candidate self transform...")
labeler->isomorphicMap(*itcs,*std::next(itcs),c_map); // 2 -> C -> 1
ops = find_transforms(*itcs,*std::next(itcs),c_map);
if(ops.size()>0) {
auto _op = ops.begin();
LOGGER("Found!\n"<<_op->info_str())
trans = std::make_pair(transition_label,*_op);
for(int ix=0;ix<NDIM;ix++) cand_shift_mag += (_op->shift[ix]) * (_op->shift[ix]);
cand_shift_mag = sqrt(cand_shift_mag);
//insert("SelfTransitions",task.returns,trans);
}
}
labeler->isomorphicMap(*itts,*itcs,c_map); // fills c_map : 2 -> C -> 1 for I
ops = find_transforms(*itts,*itcs,c_map); // finds operations
transition_label.first = t_i_l;
transition_label.second = c_i_l;
for(auto op:ops) { // should only be one....
trans = std::make_pair(transition_label,op);
insert("StateIsomorphisms",task.returns,trans);
}
labeler->isomorphicMap(*std::next(itts),*std::next(itcs),c_map); // 2 -> C -> 1 for F
f_ops = find_transforms(*std::next(itts),*std::next(itcs),c_map);
transition_label.first = t_f_l;
transition_label.second = c_f_l;
for(auto op:f_ops) { // should only be one....
trans = std::make_pair(transition_label,op);
insert("StateIsomorphisms",task.returns,trans);
}
for(auto op:ops) for(auto f_op:f_ops) {
LOGGER("Map I->I"<<ccount<<":"<<op.info_str()) // MI,SI
LOGGER("Map F->F"<<ccount<<":"<<f_op.info_str()) // MF,SF
/*
I2 = MI.I + SI = MI.iMIc.Ic + SI - MI.iMIc.Sc for MIc,Sc in SymI
F2 = MF.F + SF = MF.iMFc.Ic + SF - MF.iMFc.Sc for MFc,Sc in SymF
=> MI.iMIc = MF.iMFc, SI - MI.iMIc.Sc = SF - MF.iMFc.Sc
*/
// =?
bool compatible = bool(op.operation==f_op.operation); // assume the same at this point...
if(compatible) {
for(int ii=0;ii<NDIM;ii++) shift[ii] = op.shift[ii]-f_op.shift[ii];
bc.wrap(shift); // this should be the best wrap...
shift_mag=0.0;
for(int ii=0;ii<NDIM;ii++) shift_mag += shift[ii]*shift[ii];
if(sqrt(shift_mag)>0.2) compatible=false; // quite small
}
// try to find I->I2 op from F
PointShiftSymmetry i_sym_i,i_sym_f,cop_i,cop_f;
/* CHECK TODO
if(!compatible) for(auto sym_f:self_symmetries[t_f_l.first]) {
i_sym_f = sym_f.inverse();
cop_f = i_sym_f.compound(f_op);
std::cout<<cop_f.info_str()<<"\n";
std::cout<<"OR";
cop_f = f_op.compound(i_sym_f);
std::cout<<cop_f.info_str()<<"\n";
std::cout<<"--------------------\n";
}
*/
if (!compatible) for(auto sym_f:self_symmetries[t_f_l.first]) for(auto sym_i:self_symmetries[t_i_l.first]) {
i_sym_i = sym_i.inverse();
i_sym_f = sym_f.inverse();
cop_i = i_sym_i.compound(op);
cop_f = i_sym_f.compound(f_op);
compatible = bool(cop_i.operation==cop_f.operation);
/*
if(compatible) {
std::cout<<"cop_i==cop_f....";
for(int ii=0;ii<NDIM;ii++) shift[ii] = cop_i.shift[ii]-cop_f.shift[ii];
bc.wrap(shift);
shift_mag=0.0;
for(int ii=0;ii<NDIM;ii++) shift_mag += shift[ii]*shift[ii];
if(sqrt(shift_mag)>0.2) {
compatible=false;
std::cout<<"but "<<sqrt(shift_mag)<<">0.2A!\n";
} else std::cout<<"and it's good!\n";
}
*/
if(compatible) break;
}
if (compatible) {
LOGGER("Mapping compatible after accounting for self symmetries!\n")
transition_label.first = c_i_l;
transition_label.second = c_f_l;
TransitionSymmetry trans = std::make_pair(transition_label,op);
if(c_i_l.second==t_i_l.second) trans.second = f_op;
insert("TransitionIsomorphisms",task.returns,trans);
return;
}
}
#ifdef VERBOSE
if(ops.size()==0 || f_ops.size()==0) LOGGER("No mapping found\n")
#endif
} else {
LOGGER("NOT ISOMORPHIC PAIR ORDERING FALSE")
}
itcl = std::next(itcl,2);
itcs = std::next(itcs,2);
ccount++;
}
return;
};
std::function<void(GenericTask&)> file_init_impl = [this](GenericTask &task) {
/* to be overwritten (in impls as well) */
};
std::function<void(GenericTask&)> file_write_impl = [this](GenericTask &task) {
/* to be overwritten (in impls as well) */
};
/**
* This should expect:
* arguments: TrajectoryIndex
* arguments:InitialLabel
* inputData: InitialState, the configurations to modify
*
* This should return:
* returns: TrajectoryIndex
* returns: InitialLabel
* returns: FinalLabel
* outputData: FinalState
*/
std::function<void(GenericTask&)> modify_impl = [this](GenericTask &task){
Label initialLabel,finalLabel;
int trajectory;
extract("InitialLabel",task.arguments,initialLabel);
extract("TrajectoryIndex",task.arguments,trajectory);
insert("InitialLabel",task.returns,initialLabel);
insert("TrajectoryIndex",task.returns,trajectory);
System s;
extract("InitialState",task.inputData,s);
std::unordered_map<std::string,std::string> parameters=extractParameters(task.type,task.flavor,defaultFlavor,taskParameters);
std::string modifierType=parameters["Type"];
boost::trim(modifierType);
// DO SOMETHING
finalLabel=initialLabel;
insert("FinalLabel", task.returns, finalLabel);
};
std::function<void(GenericTask&)> filter_transition_impl = [this](GenericTask &task){
std::unordered_map<std::string,std::string>
parameters = extractParameters(task.type,task.flavor,defaultFlavor,taskParameters);
task.clearOutputs();
System reference,state;
extract("ReferenceState",task.inputData,reference);
extract("State",task.inputData,state);
double dX=0.0,dXmax=0.0;
bool valid=false;
/*
Label reference_label,state_label;
GenericTask t;
t.arguments=task.arguments;
t.type=BaseEngine::mapper.type("TASK_LABEL");
t.flavor=task.flavor;
t.clearInputs(); t.clearOutputs();
insert("State",t.inputData,reference);
BaseEngine::process(t);
extract("Label",t.returns, reference_label);
t.clearInputs(); t.clearOutputs();
insert("State",t.inputData,state);
BaseEngine::process(t);
extract("Label",t.returns, state_label);
if(reference_label!=state_label) {
*/
std::string filterType = parameters["Type"];
if(task.arguments.find("Type")!=task.arguments.end())
extract("Type",task.arguments,filterType);
boost::trim(filterType);
std::shared_ptr<AbstractTransitionFilter>
filter = transitionFilterFactory.at(filterType)();
filter->initialize(parameters);
valid = filter->isValid(reference, state, parameters);
dXmax = boost::lexical_cast<double>(parameters["dXmax"]);
dX = boost::lexical_cast<double>(parameters["dX"]);
//}
LOGGER("MDEngine::FilterTransition: "<<valid<<" dX: "<<dX<<" dXmax: "<<dXmax)
insert("Valid", task.returns, valid);
insert("dX", task.returns, dX);
insert("dXmax", task.returns, dXmax);
};
virtual void min_label_remap(GenericTask &task){
task.clearOutputs();
Label label;
GenericTask t;
t.arguments=task.arguments;
System s;
t.flavor=task.flavor;
//minimize
extract("State",task.inputData,s);
t.inputData.clear();
insert("State",t.inputData,s);
t.type = BaseEngine::mapper.type("TASK_MIN");
BaseEngine::process(t);
// label
extract("State",t.outputData,s);
t.inputData.clear();
insert("State",t.inputData,s);
t.type=BaseEngine::mapper.type("TASK_LABEL");
BaseEngine::process(t);
extract("Label",t.returns, label);
// remap
t.inputData.clear();
t.returns.clear();
insert("ReferenceState",t.inputData,s);
insert("State",t.inputData,s);
t.type=BaseEngine::mapper.type("TASK_REMAP");
BaseEngine::process(t);
bool remapped;
extract("Remapped",t.returns, remapped);
insert("Remapped",task.returns, remapped);
if(remapped) {
extract("State",t.outputData,s);
extract("Label",t.returns, label);
}
insert("Label", task.returns, label);
insert("State",label, LOCATION_SYSTEM_MIN, true, task.outputData, s);
};
/**
* read a configuration from a file, minimize, and label it.
*
* This expects:
* arguments: Filename
*
* This returns
* returns: Label
* outputData State
*/
std::function<void(GenericTask&)> init_min_impl = [this](GenericTask &task) {
Label label;
GenericTask t;
t.arguments=task.arguments;
System s;
t.flavor=task.flavor;
//read the file
t.type=BaseEngine::mapper.type("TASK_INIT_FROM_FILE");
BaseEngine::process(t);
extract("State",t.outputData,s);
//
t.inputData.clear();
insert("State",t.inputData,s);
min_label_remap(t);
extract("State",t.outputData,s);
extract("Label",t.returns, label);
insert("Label", task.returns, label);
insert("State",label, LOCATION_SYSTEM_MIN, true, task.outputData, s);
};
/**
* Implement segment generation in terms of other more basic tasks. Can be overridden in derived classes if the engine can generate segments internally.
*
* This expects:
* inputData: Minimum
* inputData: QSD (optional)
*
* This returns
* returns: Trajectory
* outputData: FinalMin
* outputData:
*/
std::function<void(GenericTask&)> segment_impl = [this](GenericTask &task){
std::unordered_map<std::string,std::string> parameters=extractParameters(task.type,task.flavor,defaultFlavor,taskParameters);
//read parameters from the task
double preCorrelationTime=boost::lexical_cast<double>(parameters["PreCorrelationTime"]);
double postCorrelationTime=boost::lexical_cast<double>(parameters["PostCorrelationTime"]);
double minimumSegmentLength=boost::lexical_cast<double>(parameters["MinimumSegmentLength"]);
double blockTime=boost::lexical_cast<double>(parameters["BlockTime"]);
int nDephasingTrialsMax=boost::lexical_cast<int>(parameters["MaximumDephasingTrials"]);
bool reportIntermediates=boost::lexical_cast<bool>(parameters["ReportIntermediates"]);
int segmentFlavor=(taskParameters.count(std::make_pair(task.type,task.flavor))>0 ? task.flavor : defaultFlavor);
std::set<int> contributeSegmentsTo;
std::set<int> contributeStatisticsTo;
if(parameters.count("ContributeSegmentsTo")>0) {
std::istringstream is( parameters["ContributeSegmentsTo"]);
contributeSegmentsTo=std::set<int>{ std::istream_iterator<int>( is ), std::istream_iterator<int>() };
}
else{
contributeSegmentsTo.insert(segmentFlavor);
}
/*
if(parameters.count("ContributeStatisticsTo")>0) {
std::istringstream is( parameters["ContributeStatisticsTo"]);
contributeStatisticsTo=std::set<int>{ std::istream_iterator<int>( is ), std::istream_iterator<int>() };
}
else{
contributeStatisticsTo.insert(segmentFlavor);
}
*/
int maximumSegmentLength;
if(parameters.count("MaximumSegmentLength")>0 ) {
maximumSegmentLength=boost::lexical_cast<int>(parameters["MaximumSegmentLength"]);
}
else{
maximumSegmentLength=25*minimumSegmentLength;
}
//create tasks
GenericTask md;
md.type=BaseEngine::mapper.type("TASK_MD");
md.flavor=task.flavor;
GenericTask min;
min.type=BaseEngine::mapper.type("TASK_MIN");
min.flavor=task.flavor;
GenericTask label;
label.type=BaseEngine::mapper.type("TASK_LABEL");;
label.flavor=task.flavor;
GenericTask remap;
remap.type=BaseEngine::mapper.type("TASK_REMAP");;
remap.flavor=task.flavor;
GenericTask initVelocities;
initVelocities.type=BaseEngine::mapper.type("TASK_INIT_VELOCITIES");;
initVelocities.flavor=task.flavor;
GenericTask filterTransitions;
filterTransitions.type=BaseEngine::mapper.type("TASK_FILTER_TRANSITION");;
filterTransitions.flavor=task.flavor;
//extract the systems we were provided
System minimum;
System reference;
System qsd;
System initial;
System current;
System currentMin;
bool gotMin=extract("Minimum",task.inputData,minimum);
bool gotQsd=extract("QSD",task.inputData,qsd);
//set the initial state
if(gotQsd) {
initial=qsd;
}
else{
initial=minimum;
}
currentMin=minimum;
Label initialLabel,currentLabel;
insert("State",label.inputData,minimum);
BaseEngine::process(label);
extract("Label",label.returns,initialLabel);
//set labels
currentLabel=initialLabel;
bool dephased=gotQsd;
//sample thermal velocities
if(not dephased) {
insert("State",initVelocities.inputData,initial);
BaseEngine::process(initVelocities);
extract("State",initVelocities.outputData,initial);
}
current=initial;
int nDephasingTrials=0;
int nOverheadBlocks=0;
while(not dephased) {
//dephasing loop
current=initial;
double elapsedTime=0;
while( elapsedTime < preCorrelationTime*0.999999999 ) {
//run md
md.inputData.clear();
insert("State",md.inputData,current);
BaseEngine::process(md);
elapsedTime+=blockTime;
nOverheadBlocks++;
extract("State",md.outputData,current);
//minimize
min.inputData.clear();
insert("State",min.inputData,current);
BaseEngine::process(min);
extract("State",min.outputData,currentMin);
//currentMin=current;
//label
label.inputData.clear();
insert("State",label.inputData,currentMin);
BaseEngine::process(label);
extract("Label",label.returns,currentLabel);
if( currentLabel == initialLabel ) {
dephased=true;
}
else{
dephased=false;
break;
}
}
nDephasingTrials++;
if(nDephasingTrials>=nDephasingTrialsMax) {
LOGGERA("DEPHASING FAILED")
if(reportIntermediates) {
insert("State",currentLabel,LOCATION_SYSTEM_MIN,true,task.outputData,currentMin);
}
break;
}
}
bool segmentIsSpliceable=false;
double lastTransitionTime=-postCorrelationTime;
int nBlocks=0;
double elapsedTime=0;
bool segmentIsValid=true;
Trajectory trajectory;
Visit v;
v.label=initialLabel;
v.duration=0;
trajectory.appendVisit(v);
v.label=currentLabel;
v.duration=0;
trajectory.appendVisit(v);
trajectory.overhead()=nOverheadBlocks;
while( !segmentIsSpliceable or elapsedTime < minimumSegmentLength*0.999999999 ) {
reference=currentMin;
//take a block of MD
md.inputData.clear();
insert("State",md.inputData,current);
BaseEngine::process(md);
extract("State",md.outputData,current);
nBlocks++;
elapsedTime+=blockTime;
//append to the trajectory
if(reportIntermediates) {
v.label=currentLabel;
}
v.duration=1;
trajectory.appendVisit(v);
min.inputData.clear();
insert("State",min.inputData,current);
BaseEngine::process(min);
extract("State",min.outputData,currentMin);
//hash current state
Label previousLabel=currentLabel;
label.inputData.clear();
insert("State",label.inputData,currentMin);
BaseEngine::process(label);
extract("Label",label.returns,currentLabel);
if( currentLabel!=previousLabel ) {
filterTransitions.clearInputs();
filterTransitions.clearOutputs();
insert("State",filterTransitions.inputData,currentMin);
insert("ReferenceState",filterTransitions.inputData,reference);
BaseEngine::process(filterTransitions);
extract("Valid",filterTransitions.returns,segmentIsValid);
lastTransitionTime=elapsedTime;
if(reportIntermediates) {
insert("State",currentLabel,LOCATION_SYSTEM_MIN,true,task.outputData,currentMin);
}
}
//a segment is spliceable if the last transition occurred at least postCorrelationTime in the past
segmentIsSpliceable=(elapsedTime-lastTransitionTime >= postCorrelationTime*0.999999999);
if(trajectory.duration()>=maximumSegmentLength) {
LOGGER("SEGMENT EXCEEDED MAXIMUM LENGTH. BAILING OUT.")
break;
}
if(not segmentIsValid) {
break;
}
}
if(not segmentIsValid) {
task.clearOutputs();
//pack an empty trajectory so that nobody waits for this segment in vain
trajectory.clear();
Visit v;
v.label=initialLabel;
v.duration=0;
trajectory.appendVisit(v);
trajectory.overhead()=nOverheadBlocks+nBlocks;
SegmentDatabase db;
std::map<int,TransitionStatistics> stats;
TransitionStatistics ts;
for(auto it=contributeSegmentsTo.begin(); it!=contributeSegmentsTo.end(); it++) {
db.add(*it,trajectory);
stats[*it]=ts;
}
//pack the trajectory
insert("Statistics",task.returns,stats);
insert("Trajectory",task.returns,db);
task.clearInputs();
bool invalid=true;
insert("InvalidTransition",task.returns,invalid);
return;
}
if(not reportIntermediates) {
v.label=currentLabel;
v.duration=0;
trajectory.appendVisit(v);
}
//leave a marker that we had to end the segment prematurely
if(!segmentIsSpliceable) {
v.label=666;
v.duration=0;
trajectory.appendVisit(v);
}
System remappedMin,remappedQSD;
Label remappedLabel;
//remap minimum and qsd to canonical representation
remap.inputData.clear();
insert("ReferenceState",remap.inputData,currentMin);
insert("State",remap.inputData,currentMin);
BaseEngine::process(remap);
bool remapped;
extract("Remapped",remap.returns,remapped);
if(remapped) {
extract("Label",remap.returns,remappedLabel);
extract("State",remap.outputData,remappedMin);
remap.inputData.clear();
insert("ReferenceState",remap.inputData,currentMin);
insert("State",remap.inputData,current);
BaseEngine::process(remap);
extract("State",remap.outputData,remappedQSD);
}
else{
remappedLabel=currentLabel;
remappedMin=currentMin;
remappedQSD=current;
}
insert("FinalMinimum",remappedLabel,LOCATION_SYSTEM_MIN,true,task.outputData,remappedMin);
//placeholder to signal a switch to a canonical representative
if(currentLabel!=remappedLabel) {
v.label=0;
v.duration=0;
trajectory.appendVisit(v);
}
v.label=remappedLabel;
v.duration=0;
trajectory.appendVisit(v);
SegmentDatabase db;
std::map<int,TransitionStatistics> stats;
TransitionStatistics ts;
ts.update(trajectory.front().label,trajectory.back().label);
for(auto it=contributeSegmentsTo.begin(); it!=contributeSegmentsTo.end(); it++) {
insert("FinalQSD",remappedLabel,*it,false,task.outputData,remappedQSD);
db.add(*it,trajectory);
stats[*it]=ts;
}
//pack the trajectory
insert("Statistics",task.returns,stats);
insert("Trajectory",task.returns,db);
task.clearInputs();
};
std::function<void(GenericTask&)> label_impl = [this](GenericTask &task){
bool canonical=false;
System s;
extract("State",task.inputData,s);
Label label=labeler->hash(s,canonical);
insert("Label",task.returns,label);
};
//joint remapping of a number of states. This assumes that all systems in the task correspond to the same state. The first state is used as a reference
std::function<void(GenericTask&)> remap_impl = [this](GenericTask &task){
std::unordered_map<std::string,std::string>
parameters=extractParameters(task.type,task.flavor,defaultFlavor,taskParameters);
bool canonical=boost::lexical_cast<bool>(parameters["Canonical"]);
bool remapped=false;
if(canonical) {
System reference;
System s;
bool gotRef=extract("ReferenceState",task.inputData,reference);
bool gotState=extract("State",task.inputData,s);
if (gotRef and gotState) {
std::map<int,int> canonicalMap;
Label lb;
labeler->canonicalMap(reference,canonicalMap,lb);
s.remap(canonicalMap);
remapped=true;
insert("Remapped",task.returns,remapped);
insert("Label",task.returns,lb);
auto it=task.inputData.find("State");
insert("State",lb,it->second.location, it->second.shared,task.outputData,s);
}
} else insert("Remapped",task.returns,remapped);
};
std::function<void(GenericTask&)> carve_impl = [this](GenericTask &task) {
task.clearOutputs(); // just in case
std::unordered_map<std::string,std::string> parameters=\
extractParameters(task.type,task.flavor,defaultFlavor,taskParameters);
//read parameters from the task
std::string carve_compute=safe_extractor<std::string>(parameters,"CarveCompute","NULL");
double thresh=safe_extractor<double>(parameters,"Threshold",5.0);
double scale=safe_extractor<double>(parameters,"RelativeCutoff",1.0);
std::list<System> sysl;
GenericTask centro;
if(BaseEngine::local_rank==0) LOGGER("CarveCompute: "<<carve_compute);
centro.type = BaseEngine::mapper.type("TASK_CARVE_COMPUTE");
insert("CarveCompute",centro.arguments,carve_compute);
extract("State",task.inputData,sysl);
task.clearInputs();
if(BaseEngine::local_rank==0)
LOGGER("TADEngine::carve_impl : FOUND "<<sysl.size()<<" STATES")
for(auto &s : sysl) {
Cell bc = s.getCell();
System thr_s;
int clusters=1,thr_N=0;
std::array<double,3> position={0.,0.,0.},fatom={0.,0.,0.},temp={0.,0.,0.};
double temp_double=0.0;
std::vector<double> csl;
if(carve_compute=="NULL") {
LOGGER("TADEngine::carve_impl : carve_compute==NULL; assigning center of mass position")
insert("Clusters",task.returns,clusters);
insert("Position",task.returns,position);
thr_N = s.getNAtoms();
for(int i=0; i<thr_N;i++) for(int j=0;j<3;j++)
position[j] += s.getPosition(i,j)/double(thr_N);
thr_N = 0;
} else {
centro.clearInputs(); centro.clearOutputs();
insert("State",centro.inputData,s);
insert("CarveCompute",centro.arguments,carve_compute);
BaseEngine::process(centro);
extract("CarveComputeVector",centro.outputData,csl);
thr_s.setCell(s.getCell());
for(int i=0; i<csl.size();i++) if(csl[i]>thresh) thr_N++;
thr_s.setNAtoms(thr_N);
if(thr_N==0&&BaseEngine::local_rank==0)
LOGGERA("TADEngine::carve_impl : No atoms above threshold!")
}
if(thr_N==0) {
insert("ThreshState",task.outputData,s);
} else {
thr_N=0;
if(BaseEngine::local_rank==0)
LOGGER("TADEngine::carve_impl : Thresholding:")
// Build new system from above-threshold atoms, scaled by RelativeCutoff
for(int i=0; i<csl.size();i++) if(csl[i]>thresh) {
if(BaseEngine::local_rank==0)
LOGGER(s.getUniqueID(i)<<" "<<s.getPosition(i,0)<<" "<<s.getPosition(i,1)<<" "<<s.getPosition(i,2)<<" "<<csl[i]<<" "<<thresh)
// new ID
thr_s.setUniqueID(thr_N,s.getUniqueID(i));
// snap to first position
if(thr_N==0) for(int j=0;j<3;j++) fatom[j] = s.getPosition(i,j);
for(int j=0;j<3;j++) temp[j] = s.getPosition(i,j)-fatom[j];
bc.wrapc(temp);
// new_x_j = pbc(x_j-x_i) + x_i
for(int j=0;j<3;j++) thr_s.setPosition(thr_N,j,(fatom[j]+temp[j])/scale);
thr_s.setSpecies(thr_N,s.getSpecies(i));
thr_N++;
}
// Find clusters
std::vector<int> cluster_occ;
clusters = labeler->connectedComponents(thr_s,cluster_occ);
// rescale positions
for(int i=0;i<thr_N;i++) for(int j=0;j<3;j++) {
temp_double = thr_s.getPosition(i,j) * scale;
thr_s.setPosition(i,j,temp_double);
}
insert("ThreshState",task.outputData,thr_s);
// find size and center of mass of each cluster
std::vector<int> rocc(clusters,0); // size
std::vector<std::array<double,3>> rocp(clusters,{0.,0.,0.}); // position
for(int i=0;i<cluster_occ.size();i++) {
for(int j=0;j<3;j++) rocp[cluster_occ[i]][j] += thr_s.getPosition(i,j);
rocc[cluster_occ[i]]++;
}
// Return position of largest cluster
int max_cl=0;
for(int i=0;i<clusters;i++) {
if(rocc[i]>0) for(int j=0;j<3;j++) rocp[i][j] /= float(rocc[i]);
if(BaseEngine::local_rank==0)
LOGGER("Cluster "<<i+1<<" : "<<rocc[i]<<" atoms, position :"<<rocp[i][0]<<" "<<rocp[i][1]<<" "<<rocp[i][2])
if(rocc[i]>rocc[max_cl]) max_cl = i;
}
for(int j=0;j<3;j++) position[j] = rocp[max_cl][j];
}
if(BaseEngine::local_rank==0)
LOGGER("TADEngine::carve_impl : NClusters = "<<clusters);
if(BaseEngine::local_rank==0)
LOGGER("TADEngine::carve_impl : Position = ["<<position[0]<<" "<<position[1]<<" "<<position[2]<<"]")
insert("Position",task.returns,position);
insert("Clusters",task.returns,clusters);
}
};
/* HELPER FUNCTIONS */
// two is not passed by reference due to remap. finds mapping T,d such that T(y)+d = x for y,x == two,one
std::set<PointShiftSymmetry> find_transforms(System &one, System two, std::map<int,int> &map) {
if(BaseEngine::local_rank==0)
LOGGER("MDEngine::find_transforms");
Cell bc = one.getCell();
int natoms = one.getNAtoms();
PointShiftSymmetry op;
std::set<PointShiftSymmetry> ops;
std::array<double,NDIM*NDIM> T;
double min_d = 0.0, temp_d=0.0, a_mag=0.0;
std::array<double,NDIM> temp,shift,cc={0.,0.,0.};
for(int j=0;j<NDIM;j++) for(int k=0;k<NDIM;k++) cc[j] += bc.rsp[j][k]/2.0;
two.remap(map);
if(BaseEngine::local_rank==0){
LOGGER("cell center: "<<cc[0]<<" "<<cc[1]<<" "<<cc[2])
LOGGER("cell origin: "<<bc.origin[0]<<" "<<bc.origin[1]<<" "<<bc.origin[2])
}
// Rotate around, then shift: X-c = G.(X-c) + d_i
for(int operation=0; operation<48; operation++) {
op.transform_matrix(T,operation); // fill transform matrix
for(int j=0;j<NDIM;j++) {
shift[j] = 0.0;
for(int k=0;k<NDIM;k++)
shift[j] += T[3*j+k]*(two.getPosition(0,k));//-two.getPosition(ca_two,k));//-cc[k]);
shift[j] -= (one.getPosition(0,j));//-one.getPosition(ca_one,j));//-cc[j]); // shift = T(x1[0]) - x0[0]
}
bool complete=true;
for(unsigned i=0; i<natoms; i++) {
for(int j=0;j<NDIM;j++) {
temp[j] = 0.;
for(int k=0;k<NDIM;k++)
temp[j] += T[NDIM*j+k] * (two.getPosition(i,k));//-two.getPosition(ca_two,k));//-cc[k]); // T(x1[i])
temp[j] -= one.getPosition(i,j);//-one.getPosition(ca_one,j);//-cc[j];
temp[j] -= shift[j]; // T(x1[i]) - x0[i] - shift = T(x1[i]-x1[0]) - (x0[i]-x0[0])
}
bc.wrapc(temp);
for(int j=0;j<NDIM;j++) if(temp[j] * temp[j] > 0.05) {
complete=false;
break;
}
}
if(complete) {
bc.wrap(shift);
if(BaseEngine::local_rank==0){
LOGGER(" ["<<T[0]<<" "<<T[1]<<" "<<T[2]<<"]")
LOGGER("matrix:["<<T[3]<<" "<<T[4]<<" "<<T[5]<<"]")
LOGGER(" ["<<T[6]<<" "<<T[7]<<" "<<T[8]<<"]")
LOGGER("shift: ["<<shift[0]<<" "<<shift[1]<<" "<<shift[2]<<"]")
}
op.operation=operation;
op.matrix=T;
for(int j=0;j<NDIM;j++) op.shift[j] = shift[j];
op.valid = true;
ops.insert(op);
}
}
return ops;
};
// VF2-free implementation
bool find_transforms_direct(System &one, System two, PointShiftSymmetry &op, int operation) {
if(BaseEngine::local_rank==0) LOGGER("MDEngine::find_transforms_direct");
Cell bc = one.getCell();
int natoms = one.getNAtoms();
bool complete=true;
unsigned min_i2;
std::array<double,NDIM*NDIM> T;
double min_d = 0.0, temp_d=0.0, a_mag=0.0;
std::array<double,NDIM> temp,cc,cc2,temp2,shift;
std::vector<int> count(natoms,0);
for(int j=0;j<NDIM;j++) {
cc[j] = 0.0;
for(int k=0;k<NDIM;k++) cc[j] += bc.rsp[j][k]/2.0;
}
if(BaseEngine::local_rank==0) {
LOGGER("cell center: "<<cc[0]<<" "<<cc[1]<<" "<<cc[2])
LOGGER("cell origin: "<<bc.origin[0]<<" "<<bc.origin[1]<<" "<<bc.origin[2])
}
// Rotate around position with transform matrix
// one : centered_cluster + com
// two : T.centered_cluster + com
op.transform_matrix(T,operation);
for(int j=0;j<NDIM;j++) temp2[j] = 0.0;
for(unsigned i=0; i<natoms; i++)
for(int j=0;j<NDIM;j++) temp2[j] += one.getPosition(i,j) / natoms;
for(unsigned i=0; i<natoms; i++) {
for(int j=0;j<NDIM;j++) {
temp[j] = 0.;
for(int k=0;k<NDIM;k++)
temp[j] += T[NDIM*j+k] * (one.getPosition(i,k)-temp2[k]);
two.setPosition(i,j,temp[j]+temp2[j]);
}
}
// O(N^2)-O(N^3) closest remapping
for(unsigned s_i=0; s_i<natoms; s_i++) {
// shift vector
for(int j=0;j<NDIM;j++)
shift[j] = two.getPosition(s_i,j)-one.getPosition(0,j);
complete=true;
for(unsigned i1=0; i1<natoms; i1++) count[i1] = 0;
for(unsigned i1=0; i1<natoms; i1++) {
min_d = 100000000.0;
min_i2 = i1;
for(unsigned i2=0; i2<natoms; i2++) {
for(int j=0;j<NDIM;j++)
temp[j] = two.getPosition(i2,j)-one.getPosition(i1,j)-shift[j];
bc.wrapc(temp);
temp_d = 0.0; for(int j=0;j<NDIM;j++) temp_d += temp[j]*temp[j];
if(temp_d<min_d) {
min_i2 = i2;
min_d = temp_d;
}
}
if(min_d>0.01) break;
else count[min_i2] += 1;
}
for(unsigned i1=0; i1<natoms; i1++) if(count[i1]!=1) complete=false;
if(complete) break;
}
if(!complete) return false;
/*
Match found!
new = T.old + shift
*/
bc.wrap(shift);
if(BaseEngine::local_rank==0) {
LOGGER(" ["<<T[0]<<" "<<T[1]<<" "<<T[2]<<"]")
LOGGER("matrix:["<<T[3]<<" "<<T[4]<<" "<<T[5]<<"]")
LOGGER(" ["<<T[6]<<" "<<T[7]<<" "<<T[8]<<"]")
LOGGER("shift: ["<<shift[0]<<" "<<shift[1]<<" "<<shift[2]<<"]")
}
op.operation=operation;
op.matrix=T;
for(int j=0;j<NDIM;j++) op.shift[j] = shift[j];
op.valid = true;
return true;
};
bool SelfSymmetriesVF2(System &one, std::set<PointShiftSymmetry> &syms,bool return_maps=false) {
if(BaseEngine::local_rank==0) LOGGER("MDEngine::SelfSymmetriesVF2");
std::list<std::map<int,int>> amaps;
syms.clear();
labeler->isomorphicSelfMaps(one,amaps);
if(BaseEngine::local_rank==0) LOGGER("FOUND "<<amaps.size()<<" SELF MAPS");
int count = 0;
for (auto &map: amaps) {
auto ops = find_transforms(one, one, map);
for(auto op: ops) {
if(return_maps) op.map = map;
syms.insert(op);
}
count++;
if(count>48) {
if(BaseEngine::local_rank==0) LOGGER("TRIED 96 SELF MAPS, FOUND "<<syms.size()<<" OPERATIONS. EXITING")
break;
}
}
return bool(amaps.size()<=syms.size());
};
bool SelfSymmetriesDirect(System &one, std::set<PointShiftSymmetry> &syms) {
if(BaseEngine::local_rank==0) LOGGER("MDEngine::SelfSymmetriesDirect");
bool found_transform;
PointShiftSymmetry op;
for(int operation=0; operation<48; operation++)
if(find_transforms_direct(one,one,op,operation)) syms.insert(op);
if(BaseEngine::local_rank==0)
LOGGER("TRIED 48 SELF MAPS, FOUND "<<syms.size()<<" OPERATIONS. EXITING")
return true;
};
};
#endif
|
#include <iostream>
#include <numeric>
using namespace std;
int main() {
int b, k;
cin >> b >> k;
int a[k];
for (int i = 0; i < k; ++i) cin >> a[i];
if (b & 1) {
cout << (accumulate(a, a + k, 0) & 1 ? "odd" : "even") << endl;
} else {
cout << (a[k - 1] & 1 ? "odd" : "even") << endl;
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2007 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#include "modules/encodings/encoders/utf16-encoder.h"
int UTF16toUTF16OutConverter::Convert(const void *src, int len, void *dest,
int maxlen, int *read_ext)
{
if (m_firstcall)
{
if (maxlen < 2)
{
// No space to add BOM
*read_ext = 0;
return 0;
}
// Add a BOM to the output string
UINT16 *output = reinterpret_cast<UINT16 *>(dest);
*(output ++) = 0xFEFF;
m_firstcall = FALSE;
// Do the rest of the buffer
return Convert(src, len, output, maxlen - sizeof (UINT16), read_ext)
+ sizeof (UINT16);
}
// Just copy
if (len > maxlen) len = maxlen;
op_memcpy(dest, src, len);
*read_ext = len;
m_num_converted += len / 2;
return len;
}
int UTF16toUTF16OutConverter::ReturnToInitialState(void *)
{
// Add a BOM to the next buffer as well
m_firstcall = TRUE;
return 0;
}
void UTF16toUTF16OutConverter::Reset()
{
this->OutputConverter::Reset();
m_firstcall = TRUE;
}
const char *UTF16toUTF16OutConverter::GetDestinationCharacterSet()
{
return "utf-16";
}
|
#define BOOST_SP_DISABLE_THREADS
#include <iostream>
#include <iomanip>
#include <dax/Types.h>
#include "Point3D.h"
#include "tests/RandomPoints3D.h"
#include "PointLocator.h"
// main
int main(void)
{
// first generate a bunch of random points
RandomPoints3D random;
random.setExtent(0, 3, 0, 3, 0, 3);
random.setPointCount(20);
random.generate();
std::vector<Point3D> points = random.getPoints();
points.push_back(Point3D(0.99, 0.99, 0.99));
// translate Point2D to dax::vector2
std::vector<dax::Vector3> daxPoints(points.size());
for (unsigned int i = 0; i < points.size(); ++i)
{
Point3D point = points[i];
dax::Vector3 daxvec(point.x(), point.y(), point.z());
daxPoints[i] = daxvec;
}
// print input
std::cout << std::fixed;
std::cout.precision(4);
std::cout << std::setw(10) << "X: ";
for (unsigned int i = 0; i < daxPoints.size(); ++i)
std::cout << std::setw(6) << daxPoints[i][0] << ", ";
std::cout << std::endl;
std::cout << std::setw(10) << "Y: ";
for (unsigned int i = 0; i < daxPoints.size(); ++i)
std::cout << std::setw(6) << daxPoints[i][1] << ", ";
std::cout << std::endl;
std::cout << std::setw(10) << "Z: ";
for (unsigned int i = 0; i < daxPoints.size(); ++i)
std::cout << std::setw(6) << daxPoints[i][2] << ", ";
std::cout << std::endl;
// use PointLocator class
PointLocator locator;
locator.setDimensions(3, 3, 3);
locator.setBounds(3, 3, 3);
locator.setPoints(daxPoints);
locator.build();
// outputs
std::vector<dax::Vector3> sortPoints = locator.getSortPoints();
std::vector<dax::Id> pointStarts = locator.getPointStarts();
std::vector<int> pointCounts = locator.getPointCounts();
// print
std::cout << std::fixed;
std::cout.precision(4);
std::cout << std::setw(10) << "Sort X: ";
for (unsigned int i = 0; i < sortPoints.size(); ++i)
std::cout << std::setw(6) << sortPoints[i][0] << ", ";
std::cout << std::endl;
std::cout << std::setw(10) << "Sort Y: ";
for (unsigned int i = 0; i < sortPoints.size(); ++i)
std::cout << std::setw(6) << sortPoints[i][1] << ", ";
std::cout << std::endl;
std::cout << std::setw(10) << "Sort Z: ";
for (unsigned int i = 0; i < sortPoints.size(); ++i)
std::cout << std::setw(6) << sortPoints[i][2] << ", ";
std::cout << std::endl;
std::cout << std::setw(10) << "Pt Start: ";
for (unsigned int i = 0; i < pointStarts.size(); ++i)
std::cout << std::setw(3) << pointStarts[i] << ", ";
std::cout << std::endl;
std::cout << std::setw(10) << "Pt Count: ";
for (unsigned int i = 0; i < pointCounts.size(); ++i)
std::cout << std::setw(3) << pointCounts[i] << ", ";
std::cout << std::endl;
// binning a point
while (true)
{
// inputs for binPoint
float x, y, z;
std::cout << std::setw(10) << "X: ";
std::cin >> x;
std::cout << std::setw(10) << "Y: ";
std::cin >> y;
std::cout << std::setw(10) << "Z: ";
std::cin >> z;
dax::Vector3 point(x, y, z);
// find the bucket id the point belongs to
dax::Id id = locator.locatePoint(point);
// find the points in the same bucket
std::vector<dax::Vector3> points = locator.getBucketPoints(id);
// print
std::cout << std::setw(10) << "Bucket Id: " << id << std::endl;
std::cout << std::setw(10) << "Pts X: ";
for (unsigned int i = 0; i < points.size(); ++i)
std::cout << std::setw(6) << points[i][0] << ", ";
std::cout << std::endl;
std::cout << std::setw(10) << "Pts Y: ";
for (unsigned int i = 0; i < points.size(); ++i)
std::cout << std::setw(6) << points[i][1] << ", ";
std::cout << std::endl;
std::cout << std::setw(10) << "Pts Z: ";
for (unsigned int i = 0; i < points.size(); ++i)
std::cout << std::setw(6) << points[i][2] << ", ";
std::cout << std::endl;
}
return 0;
}
|
#include"conio.h"
#include"stdio.h"
void main(void)
{
int a,b;
clrscr();
for(a=3; a<=19; a+=3)
printf("%d ",a);
getch();
}
|
#include <iostream>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <cmath>
#include <queue>
#include <climits>
#include <stack>
#include <map>
#include <set>
using namespace std;
int const MAXN = 4100;
int arreglo[MAXN];
int solucionar2(int actual,int a)
{
if(actual<a)
{
return 0;
}
else if(actual==a)
{
return 1;
}
else if(arreglo[actual-a]==0)
{
return 0;
}
else
{
return arreglo[actual-a]+1;
}
}
int solucionar(int n,int a,int b,int c)
{
for(int i=1;i<=n;i++)
{
arreglo[i] = max(max(solucionar2(i,a),solucionar2(i,b)),solucionar2(i,c));
}
return arreglo[n];
}
int main()
{
int n,a,b,c;
while(cin>>n>>a>>b>>c)
{
for(int i=0;i<MAXN;i++)
{
arreglo[i] = 0;
}
cout<<solucionar(n,a,b,c)<<endl;;
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) Opera Software ASA 2002 - 2006
*
* Code analyzer.
*
* @author Jens Lindstrom
*/
#ifndef ES_ANALYZER_H
#define ES_ANALYZER_H
#include "modules/ecmascript/carakan/src/compiler/es_code.h"
class ES_Analyzer
{
public:
static BOOL NextInstruction(ES_CodeStatic *code, ES_CodeWord *&word);
#ifdef ES_NATIVE_SUPPORT
ES_Analyzer(ES_Context *context, ES_Code *code, BOOL loop_dispatcher = FALSE);
~ES_Analyzer();
BOOL AssumeNoIntegerOverflows();
void SetLoopIORange(unsigned start, unsigned end) { OP_ASSERT(loop_dispatcher); loop_io_start = start; loop_io_end = end; }
ES_CodeOptimizationData *AnalyzeL();
private:
ES_Context *context;
ES_Code *code;
ES_CodeWord *word;
ES_CodeOptimizationData *data;
BOOL loop_dispatcher;
unsigned loop_io_start, loop_io_end;
BOOL IsTemporary(ES_CodeWord::Index index) { return code->data->first_temporary_register <= index; }
class Input
{
public:
Input() {}
Input(ES_CodeWord::Index index)
: index(index),
has_type(FALSE),
has_forced_type(FALSE)
{
}
Input(ES_CodeWord::Index index, BOOL has_type, BOOL has_forced_type, ES_ValueType type)
: index(index),
has_type(has_type),
has_forced_type(has_forced_type),
type(type)
{
}
ES_CodeWord::Index index;
BOOL has_type, has_forced_type;
ES_ValueType type;
};
class Output
{
public:
Output() {}
Output(ES_CodeWord::Index index, BOOL optional = FALSE)
: index(index & 0x7fffffffu),
has_type(FALSE),
has_value(FALSE),
optional(optional)
{
}
Output(ES_CodeWord::Index index, BOOL has_type, const ES_ValueType type, BOOL has_value = FALSE, unsigned value_cw_index = 0, BOOL optional = FALSE)
: index(index & 0x7fffffffu),
has_type(has_type),
has_value(has_value),
optional(optional),
type(type),
value_cw_index(value_cw_index)
{
}
ES_CodeWord::Index index;
BOOL has_type, has_value, optional;
ES_ValueType type;
unsigned value_cw_index;
};
ES_CodeOptimizationData::RegisterAccess **register_accesses;
unsigned *register_access_counts;
ES_CodeOptimizationData::JumpTarget *previous_jump_target;
static unsigned FindRegisterAccessIndex(unsigned cw_index, ES_CodeOptimizationData::RegisterAccess *accesses, unsigned count);
void AppendAccess(unsigned register_index, const ES_CodeOptimizationData::RegisterAccess &access, BOOL final = FALSE);
void InsertAccess(unsigned register_index, const ES_CodeOptimizationData::RegisterAccess &access);
void PropagateWriteInformation(unsigned register_index, ES_CodeOptimizationData::RegisterAccess *from);
ES_CodeOptimizationData::RegisterAccess *ExplicitWriteAt(unsigned register_index, unsigned cw_index);
ES_CodeOptimizationData::RegisterAccess *ImplicitWriteAt(unsigned register_index, unsigned cw_index);
ES_CodeOptimizationData::RegisterAccess *ExplicitReadAt(unsigned register_index, unsigned cw_index);
ES_CodeOptimizationData::RegisterAccess *ImplicitReadAt(unsigned register_index, unsigned cw_index);
ES_CodeOptimizationData::RegisterAccess *WriteReadAt(unsigned register_index, unsigned cw_index);
BOOL IsTrampled(unsigned register_index);
BOOL KnownType(ES_ValueType &type, unsigned register_index, unsigned cw_index);
BOOL KnownValue(ES_Value_Internal &value, unsigned &value_cw_index, unsigned register_index, unsigned cw_index);
Output OutputFromInput(unsigned register_index, unsigned cw_index, const Input &input);
void ProcessInstruction(Input *&input, Output *&output);
void ProcessInput(unsigned cw_index, const Input &input);
void ProcessOutput(unsigned cw_index, const Output &output, BOOL is_implicit = FALSE);
BOOL ProcessJumps();
BOOL ProcessJump(unsigned from, unsigned to);
BOOL ReprocessInferredTypes();
BOOL ReprocessInferredType(unsigned cw_index, unsigned inferred_type, BOOL inferred_value, unsigned value_write_index, ES_CodeWord::Index target);
BOOL ReprocessCopy(unsigned cw_index, ES_CodeWord::Index from, ES_CodeWord::Index to);
void ProcessRShiftUnsigned(unsigned cw_index, ES_CodeWord *word, unsigned &inferred_type);
#endif // ES_NATIVE_SUPPORT
};
#endif // ES_ANALYZER_H
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmEnableLanguageCommand.h"
#include "cmExecutionStatus.h"
#include "cmMakefile.h"
bool cmEnableLanguageCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.empty()) {
status.SetError("called with incorrect number of arguments");
return false;
}
bool optional = false;
std::vector<std::string> languages;
for (std::string const& it : args) {
if (it == "OPTIONAL") {
optional = true;
} else {
languages.push_back(it);
}
}
status.GetMakefile().EnableLanguage(languages, optional);
return true;
}
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2012-2013.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
// fwComEd
#include <fwComEd/fieldHelper/MedicalImageHelpers.hpp>
#include <fwComEd/Dictionary.hpp>
#include <fwData/Vector.hpp>
#include "gdcmIO/writer/DicomDistanceWriter.hpp"
#include "gdcmIO/helper/GdcmHelper.hpp"
#include "gdcmIO/DicomDictionarySR.hpp"
namespace gdcmIO
{
namespace writer
{
//------------------------------------------------------------------------------
DicomDistanceWriter::DicomDistanceWriter()
{
SLM_TRACE_FUNC();
this->m_distances = ::boost::shared_ptr<DicomDistance>( new DicomDistance );
}
//------------------------------------------------------------------------------
DicomDistanceWriter::~DicomDistanceWriter()
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
void DicomDistanceWriter::write(::gdcm::DataSet & a_gDs) throw (::fwTools::Failed)
{
SLM_TRACE_FUNC();
::fwData::Image::csptr image = this->getConcreteObject();
SLM_ASSERT("fwData::Image not set", image);
//***** Set Distances *****//
try
{
m_distances->setFromData(image); // Change distances of image in a DICOM form
}
catch(::fwTools::Failed & e)
{
throw;
}
//***** Write Distances *****//
// Get or create a content sequence in order to insert distances
const ::gdcm::Tag contentSQTag(0x0040,0xa730); // Content Sequence
if ( !a_gDs.FindDataElement(contentSQTag) )
{// Create a content sequence
::gdcm::SmartPointer< ::gdcm::SequenceOfItems > gSQ = new ::gdcm::SequenceOfItems();
helper::GdcmData::setSQ<0x0040,0xa730>(gSQ, a_gDs);
}
// Get the content sequence of the root of document SR
::gdcm::SmartPointer< ::gdcm::SequenceOfItems > gContentSQ = a_gDs.GetDataElement(contentSQTag).GetValueAsSQ();
::fwData::Vector::sptr vectDist;
vectDist = image->getField< ::fwData::Vector >(::fwComEd::Dictionary::m_imageDistancesId);
if(vectDist)
{
for (unsigned int i = 0; i < vectDist->size(); ++i)
{// Write one distance as a child of root of document SR
this->writeDistance(i, gContentSQ);
}
}
}
//------------------------------------------------------------------------------
void DicomDistanceWriter::writeDistance(const unsigned int idx,
::gdcm::SmartPointer< ::gdcm::SequenceOfItems > a_gSq)
{
// Create one item as child
// See PS 3.16 TID 1400
::gdcm::Item gItMeasure;
gItMeasure.SetVLToUndefined();
::gdcm::DataSet & gDsMeasure = gItMeasure.GetNestedDataSet();
// Relationship Value
helper::GdcmData::setTagValue<0x0040,0xa010>(DicomDictionarySR::getRelationshipString(DicomDictionarySR::CONTAINS), gDsMeasure); // Type 1
// Type Value
helper::GdcmData::setTagValue<0x0040,0xa040>(DicomDictionarySR::getTypeString(DicomDictionarySR::NUM), gDsMeasure); //Type 1
// Concept Name Code Sequence
helper::DicomTools::createCodeSequence<0x0040,0xa043>(DicomDictionarySR::getCodeValue(DicomDictionarySR::DISTANCE),
DicomDictionarySR::getCodeScheme(DicomDictionarySR::DISTANCE),
DicomDictionarySR::getCodeMeaning(DicomDictionarySR::DISTANCE),
gDsMeasure); //Type 1C
// Create a SQ which contains NUM (measured value sequence)
::gdcm::SmartPointer< ::gdcm::SequenceOfItems > gSqNum = new ::gdcm::SequenceOfItems();
gSqNum->SetLengthToUndefined();
{
//*** Create a measured value ***//
::gdcm::Item gItNum;
gItNum.SetVLToUndefined();
::gdcm::DataSet & gDsNum = gItNum.GetNestedDataSet();
// Add numerical value
const double numValue = atof(m_distances->getDists()[ idx ].c_str());
// Numeric Value
helper::GdcmData::setTagValues<double,0x0040,0xa30a>(&numValue, 1, gDsNum); // Type 1
// Add measured units code sequence
helper::DicomTools::createCodeSequence<0x0040,0x08ea>("mm", "UCUM", "millimeter", "1.4", gDsNum);
// Add Measured value to the sequence
gSqNum->AddItem(gItNum);
}
// Add Measured value sequence to the data set
helper::GdcmData::setSQ<0x0040,0xa300>(gSqNum, gDsMeasure); // Measured Value Sequence
// Add Spatial COORDinates (SCOORD)
::boost::shared_ptr< DicomInstance > dicomInstance = this->getDicomInstance();
SCoord & currentSCOORD = m_distances->getRefSCoords()[ idx ];
const std::string & referencedFrameNumbers = m_distances->getCRefRefFrames()[ idx ];
// Split referenced frame numbers into 2 string
std::vector<std::string> splitedRefFrame;
::boost::split( splitedRefFrame, referencedFrameNumbers, ::boost::is_any_of( "," ) ); // Get each referenced frame number
SLM_ASSERT("Referenced frame numbers are corrupted", splitedRefFrame.size() == 2);
// Get the graphic data of 2 points
const std::vector< float > graphicData = currentSCOORD.getGraphicData();
// If the image storage is multi-frame
if (dicomInstance->getIsMultiFrame())
{
currentSCOORD.setContext( DicomCodedAttribute("121055", "DCM", "Path") );
// Split graphic data into 2 points
float graphicDataTmp[2];
// Get first point
graphicDataTmp[0] = graphicData[0]; graphicDataTmp[1] = graphicData[1];
currentSCOORD.setGraphicData(graphicDataTmp, 2);
// Write first SCOORD
helper::DicomSR::createSCOORD(currentSCOORD,
splitedRefFrame[0],
dicomInstance->getCRefSOPClassUID(),
dicomInstance->getCRefSOPInstanceUID(),
gDsMeasure);
// Get second point
graphicDataTmp[0] = graphicData[2]; graphicDataTmp[1] = graphicData[3];
currentSCOORD.setGraphicData(graphicDataTmp, 2);
// Write second SCOORD
helper::DicomSR::createSCOORD(currentSCOORD,
splitedRefFrame[1],
dicomInstance->getCRefSOPClassUID(),
dicomInstance->getCRefSOPInstanceUID(),
gDsMeasure);
}
else
{// else (image save in several files)
currentSCOORD.setGraphicType(DicomDictionarySR::POINT);
currentSCOORD.setContext( DicomCodedAttribute("121230", "DCM", "Path Vertex") );
// Split graphic data into 2 points
float graphicDataTmp[2];
// Get first point
graphicDataTmp[0] = graphicData[0]; graphicDataTmp[1] = graphicData[1];
currentSCOORD.setGraphicData(graphicDataTmp, 2);
// Write first SCOORD
helper::DicomSR::createSCOORD(currentSCOORD,
dicomInstance->getCRefSOPClassUID(),
dicomInstance->getCRefReferencedSOPInstanceUIDs()[ atoi(splitedRefFrame[0].c_str()) -1 ], // -1 because frame number start at 1
gDsMeasure);
// Get second point
graphicDataTmp[0] = graphicData[2]; graphicDataTmp[1] = graphicData[3];
currentSCOORD.setGraphicData(graphicDataTmp, 2);
// Write second SCOORD
helper::DicomSR::createSCOORD(currentSCOORD,
dicomInstance->getCRefSOPClassUID(),
dicomInstance->getCRefReferencedSOPInstanceUIDs()[ atoi(splitedRefFrame[1].c_str()) -1 ], // -1 because frame number start at 1
gDsMeasure);
}
// Add the distance to the content sequence of root
a_gSq->AddItem(gItMeasure);
}
} // namespace writer
} // namespace gdcmIO
|
/**
* Project: ows-qt-console
* File name: main_window.cpp
* Description: this source file describes the program's main window
*
* @author Mathieu Grzybek on 2012-04-30
* @copyright 2012 Mathieu Grzybek. All rights reserved.
* @version $Id: code-gpl-license.txt,v 1.2 2004/05/04 13:19:30 garry Exp $
*
* @see The GNU Public License (GPL) version 3 or higher
*
*
* ows-qt-console 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 GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "main_window.h"
#include "ui_main_window.h"
// TODO: think of using a function instead of a macro to be able to return the result of the RPC command
#define RPC_EXEC(command) \
try { \
command; \
} catch ( const apache::thrift::transport::TTransportException& e ) { \
QErrorMessage* error_msg; \
\
qCritical() << "Connection failed : " << e.what(); \
\
error_msg = new QErrorMessage(); \
error_msg->showMessage(e.what()); \
error_msg->exec(); \
delete error_msg; \
\
on_actionDisconnect_triggered(); \
} catch ( const apache::thrift::TException& e ) { \
QErrorMessage* error_msg; \
\
qCritical() << "Cannot get the result from the RPC call : " << e.what(); \
\
error_msg = new QErrorMessage(); \
error_msg->showMessage(e.what()); \
error_msg->exec(); \
delete error_msg; \
\
} catch ( const std::exception& e ) { \
QErrorMessage* error_msg; \
\
qCritical() << "Cannot get the result from the RPC call : " << e.what(); \
error_msg = new QErrorMessage(); \
error_msg->showMessage(e.what()); \
error_msg->exec(); \
delete error_msg; \
}
Main_Window::Main_Window(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Main_Window)
{
QStringList headers;
load_settings();
current_planning_name.clear();
headers << "Domain Name" << "Hostname" << "Port" << "Username" << "Password";
servers_model.setHorizontalHeaderLabels(headers);
ui->setupUi(this);
ui->centralWidget->setVisible(false);
ui->actionDisconnect->setDisabled(true);
ui->current_jobs_view->setModel(¤t_jobs_model);
ui->template_jobs_view->setModel(&template_jobs_model);
// ui->nodes_list->setModel(&nodes_model);
ui->auto_refresh_current_check->setChecked(true);
ui->auto_refresh_template_check->setChecked(true);
}
Main_Window::~Main_Window()
{
delete ui;
if ( rpc_client != NULL ) {
delete rpc_client;
rpc_client = NULL;
}
}
void Main_Window::on_actionManage_triggered()
{
dm_dialog = new Domains_Manager(&servers_model);
if ( dm_dialog->exec() == QDialog::Accepted) {
qDebug() << "dm_dialog -> Accepted";
save_settings();
} else {
qDebug() << "dm_dialog -> Rejected";
load_settings();
}
delete dm_dialog;
}
void Main_Window::on_actionConnect_triggered()
{
int selected_row;
int port;
QString username;
QString password;
connect_dialog = new Connect(&selected_row, &servers_model);
if ( connect_dialog->exec() == QDialog::Accepted ) {
qDebug() << "connect_dialog -> Accepted";
routing.target_node.domain_name = servers_model.item(selected_row, 0)->text().toStdString();
routing.target_node.name = servers_model.item(selected_row, 1)->text().toStdString();
routing.calling_node.domain_name = servers_model.item(selected_row, 0)->text().toStdString();
routing.calling_node.name = "ows_gui";
port = servers_model.item(selected_row, 2)->text().toInt();
username = servers_model.item(selected_row, 3)->text();
password = servers_model.item(selected_row, 4)->text();
if ( rpc_client == NULL )
rpc_client = new Rpc_Client();
if ( rpc_client->open(routing.target_node.name.c_str(), port) == true ) {
rpc_client->get_handler()->get_current_planning_name(current_planning_name, routing);
if ( populate_domain_models() == true ) {
ui->actionConnect->setEnabled(false);
ui->actionDisconnect->setEnabled(true);
ui->centralWidget->setVisible(true);
}
} else {
QErrorMessage* error_msg = new QErrorMessage();
error_msg->showMessage("Cannot connect to the selected server");
error_msg->exec();
delete error_msg;
}
}
delete connect_dialog;
}
void Main_Window::on_actionDisconnect_triggered() {
rpc_client->close();
delete rpc_client;
ui->centralWidget->setVisible(false);
ui->actionConnect->setEnabled(true);
ui->actionDisconnect->setEnabled(false);
prepare_models();
}
void Main_Window::load_settings()
{
QSettings settings;
int size;
QList<QStandardItem*> row;
servers_model.clear();
settings.beginGroup("domains_manager");
size = settings.beginReadArray("servers");
row.clear();
for ( int i = 0 ; i < size ; i++ ) {
settings.setArrayIndex(i);
row << new QStandardItem(settings.value("domain_name").toString());
qDebug() << "domain_name :" << settings.value("domain_name").toString();
row << new QStandardItem(settings.value("hostname").toString());
qDebug() << "hostname : " << settings.value("hostname").toString();
row << new QStandardItem(settings.value("port").toString());
qDebug() << "port : " << settings.value("port").toString();
row << new QStandardItem(settings.value("username").toString());
qDebug() << "username : " << settings.value("username").toString();
row << new QStandardItem(settings.value("password").toString());
qDebug() << "password : " << settings.value("password").toString();
servers_model.insertRow(i, row);
row.clear();
}
settings.endArray();
settings.endGroup();
}
void Main_Window::save_settings()
{
QSettings settings;
settings.beginGroup("domains_manager");
settings.beginWriteArray("servers");
for ( int row = 0 ; row < servers_model.rowCount() ; row++ ) {
settings.setArrayIndex(row);
settings.setValue("domain_name", servers_model.item(row, 0)->text());
qDebug() << "domain_name : " << servers_model.item(row, 0)->text();
settings.setValue("hostname", servers_model.item(row, 1)->text());
qDebug() << "hostname : " << servers_model.item(row, 1)->text();
settings.setValue("port", servers_model.item(row, 2)->text());
qDebug() << "port : " << servers_model.item(row, 2)->text();
settings.setValue("username", servers_model.item(row, 3)->text());
qDebug() << "username : " << servers_model.item(row, 3)->text();
settings.setValue("password", servers_model.item(row, 4)->text());
qDebug() << "password : " << servers_model.item(row, 4)->text();
}
settings.endArray();
settings.endGroup();
}
bool Main_Window::populate_domain_models() {
rpc::v_nodes result_template_nodes; // TODO: think of putting it into the main_window attributes
rpc::v_nodes result_running_nodes;
if ( current_planning_name.size() == 0 ) {
qCritical() << "The current planning name is empty";
return false;
}
RPC_EXEC(rpc_client->get_handler()->get_current_planning_name(current_planning_name, routing));
RPC_EXEC(rpc_client->get_handler()->get_nodes(result_template_nodes, routing))
RPC_EXEC(rpc_client->get_handler()->get_nodes(result_running_nodes, routing))
prepare_models();
qDebug() << "Number of nodes (template): " << result_template_nodes.size();
qDebug() << "Number of nodes (running): " << result_running_nodes.size();
for ( ulong i = 0 ; i < result_template_nodes.size() ; i ++ ) {
insert_nodes_model(result_template_nodes.at(i));
if ( result_running_nodes.size() > 0 )
populate_jobs_models(&result_template_nodes.at(i).jobs, &result_running_nodes.at(i).jobs);
else
populate_jobs_models(&result_template_nodes.at(i).jobs, NULL);
}
return true;
}
void Main_Window::insert_nodes_model(const rpc::t_node& n) {
QList<QStandardItem*> node_row;
node_row << new QStandardItem(n.name.c_str());
nodes_model.appendRow(node_row);
node_row.clear();
}
bool Main_Window::populate_jobs_models(const rpc::v_jobs* template_jobs, const rpc::v_jobs* current_jobs) {
QList<QStandardItem*> job_row;
ulong max_index = 0;
if ( current_jobs == NULL )
max_index = template_jobs->size();
else {
if ( template_jobs->size() > current_jobs->size() )
max_index = template_jobs->size();
else
max_index = current_jobs->size();
}
for ( ulong i = 0 ; i < max_index ; i++ ) {
if ( i < template_jobs->size() ) {
const rpc::t_job& j = template_jobs->at(i);
job_row << new QStandardItem(j.node_name.c_str());
job_row << new QStandardItem(j.name.c_str());
job_row << new QStandardItem(j.cmd_line.c_str());
job_row << new QStandardItem(build_string_from_job_state(j.state).c_str());
if ( j.state == rpc::e_job_state::WAITING) {
job_row << new QStandardItem("-");
job_row << new QStandardItem("-");
} else {
// TODO: change the way the dates are printed
job_row << new QStandardItem(QDateTime::fromTime_t(j.start_time).toString());
job_row << new QStandardItem(QDateTime::fromTime_t(j.stop_time).toString());
}
job_row << new QStandardItem(QString::number(j.weight));
template_jobs_model.appendRow(job_row);
job_row.clear();
}
if ( current_jobs != NULL && i < current_jobs->size() ) {
const rpc::t_job& j = current_jobs->at(i);
job_row << new QStandardItem(j.node_name.c_str());
job_row << new QStandardItem(j.name.c_str());
job_row << new QStandardItem(j.cmd_line.c_str());
job_row << new QStandardItem(build_string_from_job_state(j.state).c_str());
if ( j.state == rpc::e_job_state::WAITING) {
job_row << new QStandardItem("-");
job_row << new QStandardItem("-");
} else {
// TODO: change the way the dates are printed
job_row << new QStandardItem(QDateTime::fromTime_t(j.start_time).toString());
job_row << new QStandardItem(QDateTime::fromTime_t(j.stop_time).toString());
}
job_row << new QStandardItem(QString::number(j.weight));
current_jobs_model.appendRow(job_row);
job_row.clear();
}
}
return true;
}
void Main_Window::prepare_models() {
ui->current_planning_label->setText(current_planning_name.c_str());
prepare_jobs_model();
prepare_nodes_model();
}
void Main_Window::prepare_jobs_model() {
QStringList headers;
headers << "Node Name" << "Job Name" << "Command Line" << "State" << "Start Time" << "Stop Time" << "Weight";
current_jobs_model.clear();
template_jobs_model.clear();
current_jobs_model.setHorizontalHeaderLabels(headers);
template_jobs_model.setHorizontalHeaderLabels(headers);
headers.clear();
}
void Main_Window::prepare_nodes_model() {
QStringList headers;
headers << "Nodes";
nodes_model.clear();
nodes_model.setHorizontalHeaderLabels(headers);
headers.clear();
}
void Main_Window::on_nodes_tree_doubleClicked(const QModelIndex& index)
{
/*
* Have we clicked on a node or a job?
* - its parent is valid -> this is a job
*/
if ( index.parent().isValid() == false ) {
rpc::t_node template_result_node;
rpc::t_node current_result_node;
rpc::t_node node_to_get;
// Clean the main window
prepare_jobs_model();
// Get the node's jobs only
node_to_get.name = index.data().toString().toStdString().c_str();
RPC_EXEC(rpc_client->get_handler()->get_node(template_result_node, routing, node_to_get))
RPC_EXEC(rpc_client->get_handler()->get_node(current_result_node, routing, node_to_get))
// TODO: fix it
qDebug() << "node name: " << node_to_get.name.c_str();
populate_jobs_models(&template_result_node.jobs, ¤t_result_node.jobs);
} else {
/*
rpc::t_job job;
job.node_name = jobs_model.item(index.row(), 0)->text().toStdString().c_str();
job.name = jobs_model.item(index.row(), 1)->text().toStdString().c_str();
RPC_EXEC(rpc_client->get_handler()->get_job(job, routing, job))
Edit_Job_Dialog* edit_job = new Edit_Job_Dialog(&jobs_model, &nodes_tree, &nodes_model, &job, routing.calling_node.domain_name.c_str());
if ( edit_job->exec() == QDialog::Rejected ) {
delete edit_job;
return;
}
delete edit_job;
RPC_EXEC(rpc_client->get_handler()->update_job(routing.calling_node.domain_name, local_node, job))
if ( ui->auto_refresh_check->isChecked() == true )
populate_domain_model();
*/
}
}
void Main_Window::on_add_template_node_button_clicked()
{
rpc::t_node node;
Edit_Node_Dialog* add_node = new Edit_Node_Dialog(&node, routing.calling_node.domain_name.c_str());
if ( add_node->exec() == QDialog::Rejected ) {
delete add_node;
return;
}
RPC_EXEC(rpc_client->get_handler()->add_node(routing, node))
if ( ui->auto_refresh_template_check->isChecked() == true )
populate_domain_models();
delete add_node;
}
void Main_Window::on_add_template_job_button_clicked()
{
rpc::t_job job;
Edit_Job_Dialog* add_job = new Edit_Job_Dialog(&template_jobs_model, &nodes_model, &job, routing.calling_node.domain_name.c_str());
if ( add_job->exec() == QDialog::Rejected ) {
delete add_job;
return;
}
RPC_EXEC(rpc_client->get_handler()->add_job(routing, job))
if ( ui->auto_refresh_template_check->isChecked() == true )
populate_domain_models();
delete add_job;
}
void Main_Window::on_add_current_job_button_clicked()
{
rpc::t_job job;
Edit_Job_Dialog* add_job = new Edit_Job_Dialog(¤t_jobs_model, &nodes_model, &job, current_planning_name.c_str());
if ( add_job->exec() == QDialog::Rejected ) {
delete add_job;
return;
}
RPC_EXEC(rpc_client->get_handler()->add_job(routing, job))
if ( ui->auto_refresh_current_check->isChecked() == true )
populate_domain_models();
delete add_job;
}
void Main_Window::on_get_current_nodes_button_clicked()
{
populate_domain_models();
}
void Main_Window::on_get_template_nodes_button_clicked()
{
populate_domain_models();
}
|
# The Tizen .spec assumes that Emacs is not installed and therefore
# the lisp files don't get installed. When emacs is installed on the
# host, the .spec derived build rules fail. To remove the host
# environment dependency, disable the check for emacs as done before
# in http://patchwork.openembedded.org/patch/40467/
CACHED_CONFIGUREVARS += "ac_cv_prog_EMACS=no"
|
// HelpDialog.cpp : implementation file
//
#include "stdafx.h"
#include "Pinger.h"
#include "HelpDialog.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// HelpDialog dialog
HelpDialog::HelpDialog(CWnd* pParent /*=NULL*/)
: CDialog(HelpDialog::IDD, pParent)
{
//{{AFX_DATA_INIT(HelpDialog)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void HelpDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(HelpDialog)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(HelpDialog, CDialog)
//{{AFX_MSG_MAP(HelpDialog)
// NOTE: the ClassWizard will add message map macros here
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// HelpDialog message handlers
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2006 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "InfoPanel.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick/WindowCommanderProxy.h"
#include "adjunct/quick/hotlist/HotlistManager.h"
#include "adjunct/quick_toolkit/widgets/OpTreeView/OpTreeView.h"
#include "modules/widgets/WidgetContainer.h"
#include "modules/dochand/win.h"
#include "modules/dochand/winman.h"
#include "modules/inputmanager/inputmanager.h"
#include "modules/url/url_man.h"
#include "modules/doc/doc.h"
#include "modules/locale/oplanguagemanager.h"
/***********************************************************************************
**
** InfoPanel
**
***********************************************************************************/
InfoPanel::InfoPanel() : DesktopWindowSpy(TRUE), m_is_cleared(TRUE), m_needs_update(FALSE), m_is_locked(FALSE)
{
SetSpyInputContext(this, FALSE);
}
void InfoPanel::OnDeleted()
{
SetSpyInputContext(NULL, FALSE);
WebPanel::OnDeleted();
}
/***********************************************************************************
**
** GetPanelText
**
***********************************************************************************/
void InfoPanel::GetPanelText(OpString& text, Hotlist::PanelTextType text_type)
{
g_languageManager->GetString(Str::M_VIEW_HOTLIST_MENU_INFO, text);
}
/***********************************************************************************
**
** Init
**
***********************************************************************************/
OP_STATUS InfoPanel::Init()
{
RETURN_IF_ERROR(WebPanel::Init());
SetToolbarName("Info Panel Toolbar", "Info Full Toolbar");
SetName("Info");
return OpStatus::OK;
}
/***********************************************************************************
**
** OnShow
**
***********************************************************************************/
void InfoPanel::OnShow(BOOL show)
{
if (show && m_needs_update)
{
UpdateInfo(FALSE);
}
}
/***********************************************************************************
**
** UpdateInfo
**
***********************************************************************************/
void InfoPanel::UpdateInfo(BOOL clear)
{
if (m_is_locked)
return;
if (!IsAllVisible() && !clear)
{
m_needs_update = TRUE;
return;
}
m_needs_update = FALSE;
OpBrowserView* browser_view = GetTargetBrowserView();
clear = clear || !browser_view || !WindowCommanderProxy::HasCurrentDoc(browser_view->GetWindowCommander());
if (clear)
{
if (m_is_cleared)
return;
// clear
URL url = GetBrowserView()->BeginWrite();
#ifdef USE_ABOUT_FRAMEWORK
InfoPanelEmptyHTMLView htmlview(url, Str::SI_ERR_UNKNOWN_DOCUMENT);
htmlview.GenerateData();
#else
url.WriteDocumentData(UNI_L("<html></html>"));
#endif
GetBrowserView()->EndWrite(url);
m_is_cleared = TRUE;
}
else
{
URL url = GetBrowserView()->BeginWrite();
if (!WindowCommanderProxy::GetPageInfo(browser_view, url))
{
#ifdef USE_ABOUT_FRAMEWORK
InfoPanelEmptyHTMLView htmlview(url, Str::SI_IDSTR_ERROR);
htmlview.GenerateData();
#else
OpString error;
g_languageManager->GetString(Str::SI_IDSTR_ERROR, error);
url.WriteDocumentData(UNI_L("<html>"));
url.WriteDocumentData(error.CStr());
url.WriteDocumentData(UNI_L("<html>"));
#endif
}
GetBrowserView()->EndWrite(url);
m_is_cleared = FALSE;
}
}
#ifdef USE_ABOUT_FRAMEWORK
InfoPanel::InfoPanelEmptyHTMLView::InfoPanelEmptyHTMLView(URL &url, Str::LocaleString text)
: OpGeneratedDocument(url, HTML5)
, m_text(text)
{
}
OP_STATUS InfoPanel::InfoPanelEmptyHTMLView::GenerateData()
{
#ifdef _LOCALHOST_SUPPORT_
RETURN_IF_ERROR(OpenDocument(Str::S_INFOPANEL_TITLE, PrefsCollectionFiles::StyleInfoPanelFile));
#else
RETURN_IF_ERROR(OpenDocument(Str::S_INFOPANEL_TITLE));
#endif
RETURN_IF_ERROR(OpenBody(Str::LocaleString(m_text)));
return CloseDocument();
}
#endif
/***********************************************************************************
**
** OnInputAction
**
***********************************************************************************/
BOOL InfoPanel::OnInputAction(OpInputAction* action)
{
switch (action->GetAction())
{
case OpInputAction::ACTION_GET_ACTION_STATE:
{
OpInputAction* child_action = action->GetChildAction();
switch (child_action->GetAction())
{
case OpInputAction::ACTION_LOCK_PANEL:
case OpInputAction::ACTION_UNLOCK_PANEL:
{
child_action->SetSelectedByToggleAction(OpInputAction::ACTION_LOCK_PANEL, m_is_locked);
return TRUE;
}
}
break;
}
case OpInputAction::ACTION_LOCK_PANEL:
return SetPanelLocked(TRUE);
case OpInputAction::ACTION_UNLOCK_PANEL:
return SetPanelLocked(FALSE);
}
return FALSE;
}
void InfoPanel::OnTargetDesktopWindowChanged(DesktopWindow* target_window)
{
if (!(target_window && (target_window->GetType() == WINDOW_TYPE_PANEL ||
target_window->GetType() == WINDOW_TYPE_HOTLIST)))
{
UpdateInfo(GetTargetBrowserView() == NULL);
}
}
/***********************************************************************************
**
** SetPanelLocked
**
***********************************************************************************/
BOOL InfoPanel::SetPanelLocked(BOOL locked)
{
if (m_is_locked == locked)
return FALSE;
m_is_locked = locked;
if (!m_is_locked)
UpdateInfo(FALSE);
return TRUE;
}
|
#pragma once
#include "Nodes/UnaryOperations/UnaryOperationNode.hpp"
#include "Utils/NotNull.hpp"
#include <memory>
template<class Type>
struct IUnaryOperationNodesFactory
{
virtual std::unique_ptr<UnaryOperationNode<Type>> create(NotNull<ComputationNode<Type>> input) = 0;
};
|
#include <simplecpp>
Polygon::Polygon(Composite* owner)
: Sprite(canvas_width()/2, canvas_height()/2, owner){
init(NULL, 0);
}
Polygon::Polygon(const double x, const double y, const double points[][2],
int no, Composite *owner)
: Sprite(x,y,owner){
init(points,no);
}
void Polygon::reset(const double x, const double y,
const double points[][2], int no, Composite *owner){
Sprite::reset(x,y,owner);
init(points,no);
}
void Polygon::init(const double points[][2], int no_of_points){
count = no_of_points;
cout <<"Polygon init "<<count<<endl;
for(int iter = 0; iter < count; iter ++){
vertex.push_back(Position(points[iter][0], points[iter][1]));
}
show();
}
Polygon::~Polygon(){
//if(vertex) delete []vertex;
}
void Polygon::paint(Pose *p){
if(visible && vertex.size()>0 && count >0){
XPoint xpt_vertex[count];
if(p){
Pose r = Pose(*p,pose);
r.compute_res_vertex(xpt_vertex, vertex, count);
}
else pose.compute_res_vertex(xpt_vertex, vertex, count);
drawPolygon(xpt_vertex, count, color, fill);
}
}
|
class Solution {
public:
bool isPalindrome(int x) {
vector <int> v;
int res=0;
if( x == 0) return true;
while(x) {
res = x%10;
x = x/10;
if ( res < 0) return false;
else {
v.push_back(res);
}
// cout << res << endl;
}
int n = v.size();
for(int i=0; i<v.size(); i++) {
// cout << v[i] << endl;
if(v[i] == v[n-1]) {
n--;
if(n==0) return true;
// cout << n << endl;
}
else {
break;
}
}
return false;
}
};
|
/*
Name: С�״����
Copyright:
Author: Hill bamboo
Date: 2019-08-19 16:14
Description: С�״����
�ܽ
��������
1. �ù��������Ż�ʱ��ûŪ�������˳����Ϊ��j���������㣬��������ˣ�
Ӧ���Ǵ�����ǰ�㣬������ֵ�Ų��ᱻ����
2. dp���ij�ʼ��
*/
#include <bits/stdc++.h>
using namespace std;
const int maxn = 200 + 10;
const int maxm = 1e5 + 10;
bool dp[maxm];
int arr[maxn];
int n, m;
int ans;
// dp[i][j] ��ʾǰi����Ʒ�ܷ�ճ���ֵΪj
// �Ӷ� 1 <= i <= n, 0 <= j <= m
int main(int argv, char* argc[]) {
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &arr[i]);
scanf("%d", &m);
dp[0] = true;
for (int i = 1; i <= n; ++i) {
for (int j = m; j > 0; --j) { // ����˳���ǴӺ���ǰ
if (arr[i - 1] <= j) dp[j] |= dp[j - arr[i - 1]];
}
}
cout << dp[m] << endl;
return 0;
}
|
#pragma once
#include <iberbar/RHI/D3D9/Headers.h>
#include <iberbar/RHI/ShaderReflection.h>
namespace iberbar
{
namespace RHI
{
namespace D3D9
{
class CShaderReflectionBuffer;
class CShaderReflectionVariable;
class CShaderReflectionType;
class CShaderReflection;
class CShaderReflectionMember;
UShaderVariableType ConvertShaderParameterType( ID3DXConstantTable* pD3DConstantTable, D3DXHANDLE pD3DHandle, const D3DXCONSTANT_DESC& Desc, CShaderReflectionType** ppOutReflectionType );
class CShaderReflectionType
: public IShaderReflectionType
{
public:
CShaderReflectionType();
virtual ~CShaderReflectionType();
virtual int GetMemberCount() const override { return (int)m_ReflectionMembers.size(); }
virtual const IShaderReflectionMember* GetMemberByIndex( int nIndex ) const override;
virtual const IShaderReflectionMember* GetMemberByName( const char* pstrName ) const override;
virtual void GetDesc( UShaderReflectionTypeDesc* pOutDesc ) const override;
CResult Initial( ID3DXConstantTable* pD3DConstantTable, D3DXHANDLE pD3DHandle, const D3DXCONSTANT_DESC& Desc );
FORCEINLINE UShaderVariableType GetVarType() const { return m_eVarType; }
FORCEINLINE UShaderVariableClass GetVarClass() const { return m_eVarClass; }
FORCEINLINE uint32 GetElements() const { return m_nElementCount; }
FORCEINLINE uint32 GetRowCount() const { return m_nRowCount; }
FORCEINLINE uint32 GetColumnCount() const { return m_nColumnCount; }
private:
UShaderVariableType m_eVarType;
UShaderVariableClass m_eVarClass;
uint32 m_nElementCount;
uint32 m_nRowCount;
uint32 m_nColumnCount;
std::string m_strName;
std::vector<CShaderReflectionMember*> m_ReflectionMembers;
};
class CShaderReflectionVariable
: public IShaderReflectionVariable
{
public:
CShaderReflectionVariable();
virtual ~CShaderReflectionVariable();
virtual const IShaderReflectionType* GetType() const override;
virtual void GetDesc( UShaderReflectionVariableDesc* pOutDesc ) const override;
CResult Initial( ID3DXConstantTable* pD3DConstantTable, D3DXHANDLE pD3DHandle, const D3DXCONSTANT_DESC& Desc, uint32 nOffsetTotal );
FORCEINLINE const CShaderReflectionType* GetTypeInternal() const { return &m_ReflectionType; }
FORCEINLINE D3DXHANDLE GetD3DHandle() const { return m_pD3DHandle; }
FORCEINLINE uint32 GetOffset() const { return m_nOffset; }
FORCEINLINE uint32 GetTotalSize() const { return m_nTotalSize; }
FORCEINLINE uint32 GetRegisterIndex() const { return m_nRegisterIndex; }
FORCEINLINE const char* GetName() const { return m_strName.c_str(); }
private:
D3DXHANDLE m_pD3DHandle;
uint32 m_nOffset;
uint32 m_nRows;
uint32 m_nColumns;
uint32 m_nElementSize;
uint32 m_nElementCount;
uint32 m_nTotalSize;
uint32 m_nRegisterIndex;
CShaderReflectionType m_ReflectionType;
std::string m_strName;
};
class CShaderReflectionMember
: public IShaderReflectionMember
{
public:
CShaderReflectionMember();
virtual ~CShaderReflectionMember();
virtual IShaderReflectionType* GetType() override { return m_pReflectionType; }
virtual void GetDesc( UShaderReflectionMemberDesc* pOutDesc ) const override;
CResult Initial( ID3DXConstantTable* pD3DConstantTable, D3DXHANDLE pD3DHandle, const D3DXCONSTANT_DESC& Desc );
const char* GetName() { return m_strName.c_str(); }
private:
std::string m_strName;
UShaderVariableType m_eVarType;
CShaderReflectionType* m_pReflectionType;
uint32 m_nOffset;
};
class CShaderReflectionBuffer
: public IShaderReflectionBuffer
{
public:
CShaderReflectionBuffer();
virtual int GetVariableCount() const override { return GetVariableCountInternal(); }
virtual const IShaderReflectionVariable* GetVariableByIndex( int nIndex ) const override { return GetVariableByIndexInternal( nIndex ); }
virtual const IShaderReflectionVariable* GetVariableByName( const char* pstrName ) const override { return GetVariableByNameInternal( pstrName ); }
CResult Initial( ID3DXConstantTable* pD3DConstantTable );
FORCEINLINE int GetVariableCountInternal() const { return (int)m_Variables.size(); }
FORCEINLINE const CShaderReflectionVariable* GetVariableByIndexInternal( int nIndex ) const { return &m_Variables[ (size_t)nIndex ]; }
const CShaderReflectionVariable* GetVariableByNameInternal( const char* pstrName ) const;
FORCEINLINE int GetBufferSize() const { return m_nSize; }
FORCEINLINE int GetSamplerCount() const { return m_nSamplerCount; }
private:
uint32 m_nSize;
uint32 m_nSamplerCount;
std::vector<CShaderReflectionVariable> m_Variables;
};
class CShaderReflection
: public IShaderReflection
{
public:
CShaderReflection();
virtual int GetBufferCount() const { return 1; }
virtual const IShaderReflectionBuffer* GetBufferByIndex( int nIndex ) const { return &m_Buffer; }
virtual const IShaderReflectionBuffer* GetBufferByName( const char* pstrName ) const { return &m_Buffer; }
CResult Initial( ID3DXConstantTable* pD3DConstantTable );
FORCEINLINE const CShaderReflectionBuffer* GetBuffer() const { return &m_Buffer; }
private:
CShaderReflectionBuffer m_Buffer;
};
}
}
}
|
#pragma once
#include <iostream>
#include "Employee.h"
using namespace std;
class PartTimeEmployee : public Employee
{
private:
double payRate,hoursWorked;
public:
// Default Constructor
PartTimeEmployee() : Employee() {
payRate = 0.0;
hoursWorked = 0.0;
}
// Constructor
PartTimeEmployee(int a, string b, string c, double d, double e) : Employee(a, b, c) {
payRate = d;
hoursWorked = e;
}
// Set function
void setPayRate(double a) {
payRate = a;
}
void setHoursWorked(double a) {
hoursWorked = a;
}
// Get function
double getPayRate() const {
return payRate;
}
double getHoursWorked() const {
return hoursWorked;
}
// Virtual calculation function
virtual double calculatePay() const;
// Virtual print function
virtual void print() const;
~PartTimeEmployee();
};
|
#include "../InfoRetrival.h"
int main(){
InfoRetrival ir = InfoRetrival();
std::string ip = "45.101.33.45";
std::cout << "calculating geographical location of ip: " << ip << std::endl;
std::string result = ir.getCountry(ip);
std::cout << "In the end, got " << result;
}
|
#ifndef KATAKANA_H
#define KATAKANA_H
#include "mot.h"
class Katakana : public Mot
{
public:
Katakana( const string & inHiraKata, const string & inRoumaji );
virtual ~Katakana();
};
#endif
|
#include "../head/QRCodeDrawer.h"
QRCodeDrawer::QRCodeDrawer() {
outer_frame_width = 100;//外层宽边框
frame_wid = 10;//内层细边框
currentX = frame_wid+ outer_frame_width;
currentY = frame_wid+ outer_frame_width;//二维码内容区起始处为内外边框之和
rect_len = 10;//二维码单位长方形边长为10像素
code_col = 64;
code_row = 64;//二维码为64行64列
data_index = 0;//初始时读到的数据位置为0
num_row = 1;//第一行用于存放二维码序号
code_pixel_col= 2 * frame_wid + rect_len * code_col;
code_pixel_row= 2 * frame_wid + rect_len * code_row;
all_code_pixel_col = 2 * outer_frame_width + 2 * frame_wid + rect_len * code_col;
all_code_pixel_row = 2 * outer_frame_width + 2 * frame_wid + rect_len * code_row;
code=Mat(all_code_pixel_col, all_code_pixel_row, CV_8UC3, Scalar(255, 255, 255));
}
//@breif draw a frame for the code
void QRCodeDrawer::draw_frame() {
Scalar outer_frame_color= Scalar(0, 0, 0);//外层边框颜色
Scalar frame_color = Scalar(255, 255, 255); //边框颜色
Rect rect_all = Rect(0, 0, all_code_pixel_col, all_code_pixel_row); //矩形范围:起始位置xy,宽,高,包括外层和内层边框在内的整个图形
Rect rect_code_and_frame = Rect(outer_frame_width, outer_frame_width, code_pixel_col, code_pixel_row);//包括内层边框在内的矩形
Rect rect_code = Rect(currentX, currentY, rect_len * code_col, rect_len * code_row);//二维码区域,以白色为底色
Scalar white = Scalar(255, 255, 255); //白色
rectangle(code, rect_all, outer_frame_color, -1, LINE_8); //原图,矩阵范围,线颜色,线宽,线类型
rectangle(code, rect_code_and_frame, frame_color,-1,LINE_8);//内层边框
rectangle(code, rect_code, white, -1, LINE_8);//二维码有效区域
}
//@breif set the number of needed codes
void QRCodeDrawer::set_code_num() {
double length = data.length();
double coverage = (double)code_col * (code_row-num_row);
code_num = ceil(length / coverage);
}
//@breif set the binary data stored as a string
void QRCodeDrawer::set_data(string data) {
this->data = data;
}
//@breif initialize the parameters
void QRCodeDrawer::initial() {
currentX = frame_wid+ outer_frame_width;
currentY = frame_wid+ outer_frame_width;//二维码内容区起始处为内外边框之和
rect_len = 10;//二维码单位长方形边长为10像素
code_col = 64;
code_row = 64;//二维码为64行64列
code = Mat(all_code_pixel_col, all_code_pixel_row, CV_8UC3, Scalar(255, 255, 255));
}
//@breif draw the main part of the code
void QRCodeDrawer::draw_code(int count) {
Scalar black = Scalar(0, 0, 0); //黑
for (; currentY < all_code_pixel_row - frame_wid-outer_frame_width; currentY += rect_len) {
if (currentY == frame_wid+outer_frame_width) {//若正在绘制第一行
string str = "";
if(count == 0){//若开始直接为0,行数增加,直接跳过绘制
continue;
}
else {//否则开始绘制编号
while (count)
{
str = to_string(count & 1) + str;
count = count >> 1;
}
while (str.length() < 16)//用16位存放二维码编号
{
str = "0" + str;
}
int i = 0;
for (; currentX < all_code_pixel_col - frame_wid-outer_frame_width; currentX += rect_len) {
Rect rect = Rect(currentX, currentY, rect_len, rect_len); //当前要绘图的矩形
if (str[i] == '1')
rectangle(code, rect, black, -1, LINE_8);
if (i >= 15)
i = 0;
else
i++;
}
}
}
else {//否则开始绘制数据部分
int len = data.length();//数据的总长度
if (data_index >= len)
break;
for (; currentX < all_code_pixel_col - frame_wid-outer_frame_width; currentX += rect_len) {
Rect rect = Rect(currentX, currentY, rect_len, rect_len); //当前要绘图的矩形
if (data_index >= data.length())
break;
else if (data[data_index] == '1')
rectangle(code, rect, black, -1, LINE_8);
data_index++;
}
}
currentX = frame_wid+ outer_frame_width;
}
}
//@breif generate the code
void QRCodeDrawer::generate_code(string file_path) {
set_code_num();//设置所需二维码数
for (int code_count = 0; code_count < code_num; code_count++) {
initial();//还原初始数据
draw_frame();//绘制边框
draw_code(code_count);//绘制二维码区域
stringstream ss;
string num;
ss << code_count;
ss >> num;
string path = file_path + "code" + num + ".jpg";
imwrite(path,code);//保存图片
}
}
int QRCodeDrawer::getCode_num() {
return code_num;
}
|
//*-- Author :
//////////////////////////////////////////////////////////////////////////
//
// THcScintillatorPlane
//
//////////////////////////////////////////////////////////////////////////
#include "THcScintillatorPlane.h"
ClassImp(THcScintillatorPlane)
//______________________________________________________________________________
THcScintillatorPlane::THcScintillatorPlane( const char* name,
const char* description,
THaApparatus* apparatus )
: THaNonTrackingDetector(name,description,apparatus)
{
// Normal constructor with name and description
}
//______________________________________________________________________________
THcScintillatorPlane::~THcScintillatorPlane()
{
// Destructor
}
|
#ifndef RX_THREAD_H
#define RX_THREAD_H
#include <QtCore>
class Rx_thread : public QThread
{
Q_OBJECT
public:
explicit Rx_thread(QObject *parent = 0);
protected:
void run();
void timerEvent(QTimerEvent *);
signals:
void Rx_flag(QString);
void Motion_stop();
public slots:
private:
int m_id;
};
#endif // RX_THREAD_H
|
/**************************************************************************/
/*!
@file MQ135.h
@author G.Krocker (Mad Frog Labs)
@license GNU GPLv3
First version of an Arduino Library for the MQ135 gas sensor
TODO: Review the correction factor calculation. This currently relies on
the datasheet but the information there seems to be wrong.
@section HISTORY
v1.0 - First release
*/
/**************************************************************************/
#ifndef MQ135_H
#define MQ135_H
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
/// The load resistance on the board
#define RLOAD 10.0
/// Calibration resistance at atmospheric CO2 level
//#define RZERO 76.63
//#define RZERO 583.12
#define RZERO 2730.14
//#define NH3RZERO 2373.14
#define NH3RZERO 583.12
/// Parameters for calculating ppm of CO2 from sensor resistance
#define PARA 116.6020682
#define PARB 2.769034857
//Parameters for calculating ppm of NH3 sensor resistance
#define NH3PARA 37.58805473
#define NH3PARB 3.235365807
//Parameters for calculating ppm of NH3 sensor resistance
#define NH3PARA 37.58805473
#define NH3PARB 3.235365807
/// Parameters to model temperature and humidity dependence
#define CORA 0.00035
#define CORB 0.02718
#define CORC 1.39538
#define CORD 0.0018
/// Atmospheric CO2 level for calibration purposes
#define ATMOCO2 397.13
/// Atmospheric NH3 level for calibration purposes
#define ATMONH3 100
class MQ135 {
private:
uint8_t _pin;
public:
MQ135(uint8_t pin);
float getCorrectionFactor(float t, float h);
float getResistance();
float getCorrectedResistance(float t, float h);
float getPPM();
float getPPMNH3();
float getCorrectedPPM(float t, float h);
float getRZero();
float getRZeroNH3();
float getCorrectedRZero(float t, float h);
};
#endif
|
// Created on: 1997-10-29
// Created by: Roman BORISOV
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _FEmTool_SparseMatrix_HeaderFile
#define _FEmTool_SparseMatrix_HeaderFile
#include <Standard.hxx>
#include <Standard_Transient.hxx>
#include <Standard_Real.hxx>
#include <Standard_Integer.hxx>
#include <math_Vector.hxx>
class FEmTool_SparseMatrix;
DEFINE_STANDARD_HANDLE(FEmTool_SparseMatrix, Standard_Transient)
//! Sparse Matrix definition
class FEmTool_SparseMatrix : public Standard_Transient
{
public:
Standard_EXPORT virtual void Init (const Standard_Real Value) = 0;
Standard_EXPORT virtual Standard_Real& ChangeValue (const Standard_Integer I, const Standard_Integer J) = 0;
//! To make a Factorization of <me>
Standard_EXPORT virtual Standard_Boolean Decompose() = 0;
//! Direct Solve of AX = B
Standard_EXPORT virtual void Solve (const math_Vector& B, math_Vector& X) const = 0;
//! Make Preparation to iterative solve
Standard_EXPORT virtual Standard_Boolean Prepare() = 0;
//! Iterative solve of AX = B
Standard_EXPORT virtual void Solve (const math_Vector& B, const math_Vector& Init, math_Vector& X, math_Vector& Residual, const Standard_Real Tolerance = 1.0e-8, const Standard_Integer NbIterations = 50) const = 0;
//! returns the product of a SparseMatrix by a vector.
//! An exception is raised if the dimensions are different
Standard_EXPORT virtual void Multiplied (const math_Vector& X, math_Vector& MX) const = 0;
//! returns the row range of a matrix.
Standard_EXPORT virtual Standard_Integer RowNumber() const = 0;
//! returns the column range of the matrix.
Standard_EXPORT virtual Standard_Integer ColNumber() const = 0;
DEFINE_STANDARD_RTTIEXT(FEmTool_SparseMatrix,Standard_Transient)
protected:
private:
};
#endif // _FEmTool_SparseMatrix_HeaderFile
|
// Copyright (c) 2019 The NavCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "daopage.h"
#include "timedata.h"
DaoPage::DaoPage(const PlatformStyle *platformStyle, QWidget *parent) :
QWidget(parent),
clientModel(0),
walletModel(0),
table(new QTableWidget),
layout(new QVBoxLayout),
contextMenu(new QMenu),
fActive(false),
fExclude(false),
nView(VIEW_PROPOSALS),
nCurrentView(-1),
nCurrentUnit(DEFAULT_UNIT),
nFilter(FILTER_ALL),
nFilter2(FILTER_ALL),
nCurrentFilter(FILTER_ALL),
nCurrentFilter2(FILTER_ALL)
{
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
this->setLayout(layout);
CStateViewCache view(pcoinsTip);
auto *topBox = new QFrame;
topBox->setObjectName("daoTopBox");
auto *topBoxLayout = new QHBoxLayout;
topBoxLayout->setContentsMargins(QMargins());
topBox->setLayout(topBoxLayout);
auto *bottomBox = new QFrame;
auto *bottomBoxLayout = new QHBoxLayout;
bottomBoxLayout->setContentsMargins(QMargins());
bottomBox->setLayout(bottomBoxLayout);
viewLbl = new QLabel(tr("View:"));
proposalsBtn = new NavCoinPushButton(tr("Fund Proposals"));
paymentRequestsBtn = new NavCoinPushButton(tr("Payment Requests"));
consultationsBtn = new NavCoinPushButton(tr("Consultations"));
deploymentsBtn = new NavCoinPushButton(tr("Deployments"));
consensusBtn = new NavCoinPushButton(tr("Consensus Parameters"));
filterLbl = new QLabel(tr("Filter:"));
filterCmb = new QComboBox();
filter2Cmb = new QComboBox();
createBtn = new QPushButton(tr("Create New"));
excludeBox = new QCheckBox(tr("Exclude finished and expired"));
childFilterLbl = new QLabel();
backToFilterBtn = new QPushButton(tr("Back"));
warningLbl = new QLabel();
cycleProgressBar = new QProgressBar();
cycleProgressBar->setMinimum(0);
cycleProgressBar->setMaximum(GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view));
cycleProgressBar->setTextVisible(true);
cycleProgressBar->setFormat("%v/%m");
warningLbl->setObjectName("warning");
childFilterLbl->setVisible(false);
backToFilterBtn->setVisible(false);
warningLbl->setVisible(false);
fChartOpen = false;
connect(proposalsBtn, SIGNAL(clicked()), this, SLOT(viewProposals()));
connect(paymentRequestsBtn, SIGNAL(clicked()), this, SLOT(viewPaymentRequests()));
connect(consultationsBtn, SIGNAL(clicked()), this, SLOT(viewConsultations()));
connect(deploymentsBtn, SIGNAL(clicked()), this, SLOT(viewDeployments()));
connect(consensusBtn, SIGNAL(clicked()), this, SLOT(viewConsensus()));
connect(createBtn, SIGNAL(clicked()), this, SLOT(onCreateBtn()));
connect(filterCmb, SIGNAL(activated(int)), this, SLOT(onFilter(int)));
connect(filter2Cmb, SIGNAL(activated(int)), this, SLOT(onFilter2(int)));
connect(excludeBox, SIGNAL(toggled(bool)), this, SLOT(onExclude(bool)));
connect(backToFilterBtn, SIGNAL(clicked()), this, SLOT(backToFilter()));
excludeBox->setChecked(true);
topBoxLayout->addSpacing(30);
topBoxLayout->addWidget(viewLbl, 0, Qt::AlignLeft);
topBoxLayout->addSpacing(30);
topBoxLayout->addWidget(proposalsBtn);
topBoxLayout->addWidget(paymentRequestsBtn);
topBoxLayout->addWidget(consultationsBtn);
topBoxLayout->addWidget(deploymentsBtn);
topBoxLayout->addWidget(consensusBtn);
topBoxLayout->addStretch();
topBoxLayout->addWidget(new QLabel(tr("Cycle Progress")));
topBoxLayout->addWidget(cycleProgressBar);
topBoxLayout->addStretch();
bottomBoxLayout->addSpacing(30);
bottomBoxLayout->addWidget(filterLbl, 0, Qt::AlignLeft);
bottomBoxLayout->addWidget(childFilterLbl);
bottomBoxLayout->addWidget(backToFilterBtn);
bottomBoxLayout->addSpacing(38);
bottomBoxLayout->addWidget(filterCmb, 0, Qt::AlignLeft);
bottomBoxLayout->addSpacing(30);
bottomBoxLayout->addWidget(filter2Cmb, 0, Qt::AlignLeft);
bottomBoxLayout->addSpacing(30);
bottomBoxLayout->addWidget(excludeBox);
bottomBoxLayout->addWidget(warningLbl);
bottomBoxLayout->addStretch();
bottomBoxLayout->addWidget(createBtn);
layout->addWidget(topBox);
layout->addSpacing(15);
layout->addWidget(table);
layout->addWidget(bottomBox);
table->setContentsMargins(QMargins());
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setSelectionMode(QAbstractItemView::SingleSelection);
table->setFocusPolicy(Qt::NoFocus);
table->setAlternatingRowColors(true);
table->setShowGrid(false);
table->setFocusPolicy(Qt::NoFocus);
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
table->setSelectionMode(QAbstractItemView::NoSelection);
table->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
table->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
table->verticalHeader()->setDefaultSectionSize(78);
table->verticalHeader()->setVisible(false);
table->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter);
table->horizontalHeader()->setSortIndicatorShown(true);
table->horizontalHeader()->setSectionsClickable(true);
table->setContextMenuPolicy(Qt::CustomContextMenu);
table->setWordWrap(true);
connect(table, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(showContextMenu(const QPoint &)));
copyHash = new QAction(tr("Copy hash"), this);
openExplorerAction = new QAction(tr("Open in explorer"), this);
proposeChange = new QAction(tr("Propose Change"), this);
seeProposalAction = new QAction(tr("Go to parent proposal"), this);
seePaymentRequestsAction = new QAction(tr("Show payment requests from this proposal"), this);
openChart = new QAction(tr("View votes"), this);
contextMenu->addAction(copyHash);
contextMenu->addAction(openExplorerAction);
contextMenu->addSeparator();
contextMenu->addAction(openChart);
contextMenu->addSeparator();
connect(seeProposalAction, SIGNAL(triggered()), this, SLOT(onSeeProposal()));
connect(proposeChange, SIGNAL(triggered()), this, SLOT(onCreate()));
connect(seePaymentRequestsAction, SIGNAL(triggered()), this, SLOT(onSeePaymentRequests()));
connect(copyHash, SIGNAL(triggered()), this, SLOT(onCopyHash()));
connect(openExplorerAction, SIGNAL(triggered()), this, SLOT(onDetails()));
connect(openChart, SIGNAL(triggered()), this, SLOT(onViewChart()));
viewProposals();
}
void DaoPage::setWalletModel(WalletModel *model)
{
this->walletModel = model;
refresh(true);
}
void DaoPage::setWarning(QString text)
{
warningLbl->setText(text);
warningLbl->setVisible(!text.isEmpty());
}
void DaoPage::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if (clientModel) {
connect(clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(refreshForce()));
}
}
void DaoPage::setActive(bool flag)
{
fActive = flag;
// This was added to fix the button sizes on initial load
if (nLoadCount < 2) {
nLoadCount++;
viewProposals(); // This was added to fix the button sizes on initial load
}
}
void DaoPage::setView(int view)
{
nView = view;
refresh(true);
}
void DaoPage::refreshForce()
{
if (GetAdjustedTime() - nLastUpdate > 15)
{
nLastUpdate = GetAdjustedTime();
setWarning("");
refresh(true);
}
if (fChartOpen)
chartDlg->updateView();
}
void DaoPage::refresh(bool force, bool updateFilterIfEmpty)
{
int unit = DEFAULT_UNIT;
LOCK(cs_main);
if (pcoinsTip == nullptr)
return;
CStateViewCache view(pcoinsTip);
if (!view.GetAllProposals(proposalMap) || !view.GetAllPaymentRequests(paymentRequestMap) ||
!view.GetAllConsultations(consultationMap) || !view.GetAllConsultationAnswers(consultationAnswerMap))
return;
if (clientModel)
{
OptionsModel* optionsModel = clientModel->getOptionsModel();
if(optionsModel)
{
unit = optionsModel->getDisplayUnit();
}
}
cycleProgressBar->setMaximum(GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view));
cycleProgressBar->setValue((chainActive.Tip()->nHeight % GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view))+1);
if (!force && unit == nCurrentUnit && nFilter == nCurrentFilter && nFilter2 == nCurrentFilter2 &&
((nCurrentView == VIEW_PROPOSALS && proposalMap.size() == proposalModel.size()) ||
(nCurrentView == VIEW_PAYMENT_REQUESTS && paymentRequestMap.size() == paymentRequestModel.size()) ||
(nCurrentView == VIEW_CONSULTATIONS && consultationMap.size() == consultationModel.size())))
return;
initialize(proposalMap, paymentRequestMap, consultationMap, consultationAnswerMap, unit, updateFilterIfEmpty);
}
void DaoPage::initialize(CProposalMap proposalMap, CPaymentRequestMap paymentRequestMap, CConsultationMap consultationMap, CConsultationAnswerMap consultationAnswerMap, int unit, bool updateFilterIfEmpty)
{
LOCK(cs_main);
nCurrentUnit = unit;
if (nView != nCurrentView)
{
while (filterCmb->count() > 0)
filterCmb->removeItem(0);
while (filter2Cmb->count() > 0)
filter2Cmb->removeItem(0);
nCurrentView = nView;
nCurrentFilter = nFilter;
nCurrentFilter2 = nFilter2;
table->setRowCount(0);
if (nCurrentView == VIEW_PROPOSALS)
{
createBtn->setVisible(true);
createBtn->setText(tr("Create new Proposal"));
filterCmb->insertItem(FILTER_ALL, "All");
filterCmb->insertItem(FILTER_NOT_VOTED, "Not voted");
filterCmb->insertItem(FILTER_VOTED, "Voted");
filter2Cmb->insertItem(FILTER2_ALL, "All");
filter2Cmb->insertItem(FILTER2_IN_PROGRESS, "Being voted");
filter2Cmb->insertItem(FILTER2_FINISHED, "Voting finished");
if (filterHash != "")
{
filterCmb->setVisible(false);
filter2Cmb->setVisible(false);
excludeBox->setVisible(false);
backToFilterBtn->setVisible(true);
childFilterLbl->setVisible(true);
childFilterLbl->setText(tr("Showing proposal %1...").arg(filterHash.left(16)));
}
else
{
filterCmb->setVisible(true);
filter2Cmb->setVisible(true);
excludeBox->setVisible(true);
backToFilterBtn->setVisible(false);
childFilterLbl->setVisible(false);
}
table->setColumnCount(P_COLUMN_PADDING3 + 1);
table->setColumnHidden(P_COLUMN_HASH, true);
table->setColumnHidden(P_COLUMN_COLOR, false);
table->setHorizontalHeaderLabels({ "", "", tr("Name"), tr("Requests"), tr("Paid"), tr("Duration"), tr("Votes"), tr("State"), "", tr("My Votes"), "", "" });
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_TITLE, QHeaderView::Stretch);
table->horizontalHeaderItem(P_COLUMN_TITLE)->setTextAlignment(Qt::AlignLeft);
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_VOTE, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_REQUESTS, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_PAID, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_DURATION, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_MY_VOTES, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_VOTES, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_STATE, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_COLOR, QHeaderView::Fixed);
table->setColumnWidth(P_COLUMN_COLOR, 12);
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_PADDING2, QHeaderView::Fixed);
table->setColumnWidth(P_COLUMN_PADDING2, 12);
table->horizontalHeader()->setSectionResizeMode(P_COLUMN_PADDING3, QHeaderView::Fixed);
table->setColumnWidth(P_COLUMN_PADDING3, 12);
}
else if (nCurrentView == VIEW_PAYMENT_REQUESTS)
{
createBtn->setVisible(true);
createBtn->setText(tr("Create new Payment Request"));
filterCmb->insertItem(FILTER_ALL, "All");
filterCmb->insertItem(FILTER_NOT_VOTED, "Not voted");
filterCmb->insertItem(FILTER_VOTED, "Voted");
filter2Cmb->insertItem(FILTER2_ALL, "All");
filter2Cmb->insertItem(FILTER2_IN_PROGRESS, "Being voted");
filter2Cmb->insertItem(FILTER2_FINISHED, "Voting finished");
if (filterHash != "")
{
filterCmb->setVisible(false);
filter2Cmb->setVisible(false);
excludeBox->setVisible(false);
backToFilterBtn->setVisible(true);
childFilterLbl->setVisible(true);
childFilterLbl->setText(tr("Showing payment requests of %1...").arg(filterHash.left(16)));
}
else
{
filterCmb->setVisible(true);
filter2Cmb->setVisible(true);
excludeBox->setVisible(true);
backToFilterBtn->setVisible(false);
childFilterLbl->setVisible(false);
}
table->setColumnCount(PR_COLUMN_PADDING3 + 1);
table->setColumnHidden(PR_COLUMN_HASH, true);
table->setColumnHidden(PR_COLUMN_COLOR, false);
table->setHorizontalHeaderLabels({ "", "", tr("Proposal"), tr("Description"), tr("Requests"), tr("Votes"), tr("State"), "", tr("My Votes"), "", ""});
table->horizontalHeader()->setSectionResizeMode(PR_COLUMN_PARENT_TITLE, QHeaderView::Stretch);
table->horizontalHeader()->setSectionResizeMode(PR_COLUMN_TITLE, QHeaderView::Stretch);
table->horizontalHeaderItem(PR_COLUMN_PARENT_TITLE)->setTextAlignment(Qt::AlignLeft);
table->horizontalHeader()->setSectionResizeMode(PR_COLUMN_REQUESTS, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(PR_COLUMN_MY_VOTES, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(PR_COLUMN_VOTES, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(PR_COLUMN_STATE, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(PR_COLUMN_COLOR, QHeaderView::Fixed);
table->horizontalHeader()->setSectionResizeMode(PR_COLUMN_VOTE, QHeaderView::ResizeToContents);
table->setColumnWidth(PR_COLUMN_COLOR, 12);
table->horizontalHeader()->setSectionResizeMode(PR_COLUMN_PADDING2, QHeaderView::Fixed);
table->setColumnWidth(PR_COLUMN_PADDING2, 12);
table->horizontalHeader()->setSectionResizeMode(PR_COLUMN_PADDING3, QHeaderView::Fixed);
table->setColumnWidth(PR_COLUMN_PADDING3, 12);
}
else if (nCurrentView == VIEW_CONSULTATIONS)
{
createBtn->setVisible(true);
createBtn->setText(tr("Create new Consultation"));
filterCmb->insertItem(FILTER_ALL, "All");
filterCmb->insertItem(FILTER_NOT_VOTED, "Not voted");
filterCmb->insertItem(FILTER_VOTED, "Voted");
filter2Cmb->insertItem(FILTER2_ALL, "All");
filter2Cmb->insertItem(FILTER2_IN_PROGRESS, "Being voted");
filter2Cmb->insertItem(FILTER2_FINISHED, "Voting finished");
filter2Cmb->insertItem(FILTER2_LOOKING_FOR_SUPPORT, "Looking for support");
table->setColumnCount(C_COLUMN_PADDING3 + 1);
table->setColumnHidden(C_COLUMN_HASH, true);
table->setColumnHidden(C_COLUMN_COLOR, false);
table->setHorizontalHeaderLabels({ "", "", tr("Question"), tr("Possible Answers"), tr("Status"), "", tr("My Votes"), "", ""});
table->horizontalHeader()->setSectionResizeMode(C_COLUMN_TITLE, QHeaderView::Stretch);
table->horizontalHeader()->setSectionResizeMode(C_COLUMN_ANSWERS, QHeaderView::Stretch);
table->horizontalHeaderItem(C_COLUMN_TITLE)->setTextAlignment(Qt::AlignLeft);
table->horizontalHeader()->setSectionResizeMode(C_COLUMN_STATUS, QHeaderView::ResizeToContents);
table->horizontalHeaderItem(C_COLUMN_STATUS)->setTextAlignment(Qt::AlignCenter);
table->horizontalHeader()->setSectionResizeMode(C_COLUMN_MY_VOTES, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(C_COLUMN_COLOR, QHeaderView::Fixed);
table->horizontalHeader()->setSectionResizeMode(C_COLUMN_VOTE, QHeaderView::ResizeToContents);
table->setColumnWidth(C_COLUMN_COLOR, 12);
table->horizontalHeader()->setSectionResizeMode(C_COLUMN_PADDING2, QHeaderView::Fixed);
table->setColumnWidth(C_COLUMN_PADDING2, 12);
table->horizontalHeader()->setSectionResizeMode(C_COLUMN_PADDING3, QHeaderView::Fixed);
table->setColumnWidth(C_COLUMN_PADDING3, 12);
}
else if (nCurrentView == VIEW_DEPLOYMENTS)
{
createBtn->setVisible(false);
filterCmb->insertItem(FILTER_ALL, "All");
filterCmb->insertItem(FILTER_NOT_VOTED, "Not voted");
filterCmb->insertItem(FILTER_VOTED, "Voted");
filter2Cmb->insertItem(FILTER2_ALL, "All");
filter2Cmb->insertItem(FILTER2_IN_PROGRESS, "Being voted");
filter2Cmb->insertItem(FILTER2_FINISHED, "Voting finished");
table->setColumnCount(D_COLUMN_PADDING3 + 1);
table->setColumnHidden(D_COLUMN_COLOR, false);
table->setColumnHidden(D_COLUMN_TITLE, false);
table->setHorizontalHeaderLabels({"", tr("Name"), tr("Status"), "", tr("My Vote"), "", "" });
table->horizontalHeader()->setSectionResizeMode(D_COLUMN_TITLE, QHeaderView::Stretch);
table->horizontalHeaderItem(D_COLUMN_TITLE)->setTextAlignment(Qt::AlignLeft);
table->horizontalHeaderItem(D_COLUMN_STATUS)->setTextAlignment(Qt::AlignCenter);
table->horizontalHeader()->setSectionResizeMode(D_COLUMN_STATUS, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(D_COLUMN_MY_VOTES, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(D_COLUMN_VOTE, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(D_COLUMN_COLOR, QHeaderView::Fixed);
table->setColumnWidth(D_COLUMN_COLOR, 12);
table->horizontalHeader()->setSectionResizeMode(D_COLUMN_PADDING2, QHeaderView::Fixed);
table->setColumnWidth(D_COLUMN_PADDING2, 12);
table->horizontalHeader()->setSectionResizeMode(D_COLUMN_PADDING3, QHeaderView::Fixed);
table->setColumnWidth(D_COLUMN_PADDING3, 12);
}
else if (nCurrentView == VIEW_CONSENSUS)
{
createBtn->setVisible(false);
filterCmb->insertItem(FILTER_ALL, "All");
filterCmb->insertItem(FILTER_NOT_VOTED, "Not voted");
filterCmb->insertItem(FILTER_VOTED, "Voted");
filter2Cmb->insertItem(FILTER2_ALL, "All");
filter2Cmb->insertItem(FILTER2_IN_PROGRESS, "Being voted");
filter2Cmb->insertItem(FILTER2_FINISHED, "Voting finished");
table->setColumnCount(CP_COLUMN_PADDING3 + 1);
table->setColumnHidden(CP_COLUMN_COLOR, false);
table->setColumnHidden(CP_COLUMN_ID, true);
table->setColumnHidden(CP_COLUMN_HASH, true);
table->setHorizontalHeaderLabels({"", "", "", tr("Name"), tr("Current value"), tr("Status"), tr("Proposed values"), "", tr("My votes"), "", "" });
table->horizontalHeader()->setSectionResizeMode(CP_COLUMN_TITLE, QHeaderView::Stretch);
table->horizontalHeaderItem(CP_COLUMN_TITLE)->setTextAlignment(Qt::AlignLeft);
table->horizontalHeaderItem(CP_COLUMN_STATUS)->setTextAlignment(Qt::AlignCenter);
table->horizontalHeader()->setSectionResizeMode(CP_COLUMN_STATUS, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(CP_COLUMN_CURRENT, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(CP_COLUMN_PROPOSALS, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(CP_COLUMN_MY_VOTES, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(CP_COLUMN_VOTE, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(CP_COLUMN_COLOR, QHeaderView::Fixed);
table->setColumnWidth(CP_COLUMN_COLOR, 12);
table->horizontalHeader()->setSectionResizeMode(CP_COLUMN_PADDING2, QHeaderView::Fixed);
table->setColumnWidth(CP_COLUMN_PADDING2, 12);
table->horizontalHeader()->setSectionResizeMode(CP_COLUMN_PADDING3, QHeaderView::Fixed);
table->setColumnWidth(CP_COLUMN_PADDING3, 12);
}
onFilter(FILTER_ALL);
}
CStateViewCache coins(pcoinsTip);
nBadgeProposals = nBadgePaymentRequests = nBadgeConsultations = nBadgeDeployments = nBadgeConsensus = 0;
proposalModel.clear();
for (auto& it: proposalMap)
{
CProposal proposal = it.second;
uint64_t nVote = -10000;
auto v = mapAddedVotes.find(proposal.hash);
if (v != mapAddedVotes.end())
{
nVote = v->second;
}
if (proposal.CanVote(coins) && nVote == -10000)
nBadgeProposals++;
if (!filterHash.isEmpty())
{
if (proposal.hash != uint256S(filterHash.toStdString()))
continue;
}
else
{
if (nFilter != FILTER_ALL)
{
if (nFilter == FILTER_VOTED && nVote == -10000)
continue;
if (nFilter == FILTER_NOT_VOTED && nVote != -10000)
continue;
}
if (nFilter2 != FILTER2_ALL)
{
if (nFilter2 == FILTER2_IN_PROGRESS && !proposal.CanVote(coins))
continue;
if (nFilter2 == FILTER2_FINISHED && proposal.CanVote(coins))
continue;
}
}
flags fState = proposal.GetLastState();
if (fExclude && (fState == DAOFlags::REJECTED || fState == DAOFlags::EXPIRED || proposal.GetAvailable(coins) == 0))
continue;
if (mapBlockIndex.count(proposal.txblockhash) == 0)
continue;
uint64_t deadline = proposal.nDeadline;
uint64_t deadline_d = std::floor(deadline/86400);
uint64_t deadline_h = std::floor((deadline-deadline_d*86400)/3600);
uint64_t deadline_m = std::floor((deadline-(deadline_d*86400 + deadline_h*3600))/60);
// Show appropriate amount of figures
std::string s_deadline = "";
if(deadline_d >= 14)
s_deadline = std::to_string(deadline_d) + std::string(" Days");
else
s_deadline = std::to_string(deadline_d) + std::string(" Days\n") + std::to_string(deadline_h) + std::string(" Hours\n") + std::to_string(deadline_m) + std::string(" Minutes");
QString status = QString::fromStdString(proposal.GetState(chainActive.Tip()->GetBlockTime(), coins)).replace(", ","\n");
ProposalEntry p = {
it.first,
"#6666ff",
QString::fromStdString(proposal.strDZeel).left(150) + (proposal.strDZeel.size() > 150 ? "..." : ""),
NavCoinUnits::formatWithUnit(unit, proposal.nAmount, false, NavCoinUnits::separatorAlways),
NavCoinUnits::formatWithUnit(unit, proposal.nAmount - proposal.GetAvailable(coins), false, NavCoinUnits::separatorAlways),
QString::fromStdString(s_deadline),
proposal.nVotesYes ? proposal.nVotesYes : 0,
proposal.nVotesNo ? proposal.nVotesNo : 0,
proposal.nVotesAbs ? proposal.nVotesAbs : 0,
proposal.nVotingCycle,
status,
proposal.CanVote(coins),
nVote,
(uint64_t)mapBlockIndex[proposal.txblockhash]->GetBlockTime()
};
switch (proposal.GetLastState())
{
case DAOFlags::NIL:
{
p.color = "#ffdd66";
break;
}
case DAOFlags::ACCEPTED:
{
p.color = "#66ff66";
break;
}
case DAOFlags::REJECTED:
{
p.color = "#ff6666";
break;
}
case DAOFlags::EXPIRED:
{
p.color = "#ff6600";
break;
}
}
proposalModel << p;
}
std::sort(proposalModel.begin(), proposalModel.end(), [](const ProposalEntry &a, const ProposalEntry &b) {
if (a.ts == b.ts)
return a.hash > b.hash;
else
return a.ts > b.ts;
});
paymentRequestModel.clear();
for (auto& it: paymentRequestMap)
{
CProposal proposal;
CPaymentRequest prequest = it.second;
uint64_t nVote = -10000;
auto v = mapAddedVotes.find(prequest.hash);
if (v != mapAddedVotes.end())
{
nVote = v->second;
}
if (prequest.CanVote(coins) && nVote == -10000)
nBadgePaymentRequests++;
if (!filterHash.isEmpty())
{
if (prequest.proposalhash != uint256S(filterHash.toStdString()))
continue;
}
else
{
if (nFilter != FILTER_ALL)
{
if (nFilter == FILTER_VOTED && nVote == -10000)
continue;
if (nFilter == FILTER_NOT_VOTED && nVote != -10000)
continue;
}
if (nFilter2 != FILTER2_ALL)
{
if (nFilter2 == FILTER2_IN_PROGRESS && !prequest.CanVote(coins))
continue;
if (nFilter2 == FILTER2_FINISHED && prequest.CanVote(coins))
continue;
}
}
flags fState = prequest.GetLastState();
if (fExclude && (fState == DAOFlags::PAID || fState == DAOFlags::ACCEPTED || fState == DAOFlags::REJECTED || fState == DAOFlags::EXPIRED))
continue;
if (mapBlockIndex.count(prequest.txblockhash) == 0)
continue;
if (!coins.GetProposal(prequest.proposalhash, proposal))
continue;
QString status = QString::fromStdString(prequest.GetState(coins)).replace(", ","\n");
PaymentRequestEntry p = {
it.first,
QString::fromStdString(prequest.strDZeel).left(150) + (prequest.strDZeel.size() > 150 ? "..." : ""),
QString::fromStdString(proposal.strDZeel).left(150) + (proposal.strDZeel.size() > 150 ? "..." : ""),
"#6666ff",
NavCoinUnits::formatWithUnit(unit, prequest.nAmount, false, NavCoinUnits::separatorAlways),
prequest.nVotesYes ? prequest.nVotesYes : 0,
prequest.nVotesNo ? prequest.nVotesNo : 0,
prequest.nVotesAbs ? prequest.nVotesAbs : 0,
proposal.nVotingCycle,
status,
prequest.CanVote(coins),
nVote,
(uint64_t)mapBlockIndex[prequest.txblockhash]->GetBlockTime()
};
switch (prequest.GetLastState())
{
case DAOFlags::NIL:
{
p.color = "#ffdd66";
break;
}
case DAOFlags::ACCEPTED:
{
p.color = "#66ff66";
break;
}
case DAOFlags::REJECTED:
{
p.color = "#ff6666";
break;
}
case DAOFlags::EXPIRED:
{
p.color = "#ff6600";
break;
}
}
paymentRequestModel << p;
}
std::sort(paymentRequestModel.begin(), paymentRequestModel.end(), [](const PaymentRequestEntry &a, const PaymentRequestEntry &b) {
if (a.ts == b.ts)
return a.hash > b.hash;
else
return a.ts > b.ts;
});
consultationModel.clear();
std::map<int, ConsultationConsensusEntry> mapConsultationConsensus;
for (auto& it: consultationMap)
{
CConsultation consultation = it.second;
if (mapBlockIndex.count(consultation.txblockhash) == 0)
continue;
CBlockIndex* pindex = mapBlockIndex[consultation.txblockhash];
uint64_t nVote = -10000;
auto v = mapAddedVotes.find(consultation.hash);
if (v != mapAddedVotes.end())
{
nVote = v->second;
}
QVector<ConsultationAnswerEntry> answers;
QStringList myVotes;
if (nVote == -1)
{
myVotes << tr("Abstain");
}
flags fState = consultation.GetLastState();
if (!consultation.IsRange())
{
for (auto& it2: consultationAnswerMap)
{
CConsultationAnswer answer;
if (!coins.GetConsultationAnswer(it2.first, answer))
continue;
if (answer.parent != consultation.hash)
continue;
if (!answer.IsSupported(coins) && fState != DAOFlags::NIL)
continue;
if (!consultation.IsRange())
{
auto v = mapAddedVotes.find(answer.hash);
if (v != mapAddedVotes.end() && v->second == 1)
{
if (consultation.IsAboutConsensusParameter())
myVotes << QString::fromStdString(FormatConsensusParameter((Consensus::ConsensusParamsPos)consultation.nMin, answer.sAnswer));
else
myVotes << QString::fromStdString(answer.sAnswer);
}
}
ConsultationAnswerEntry a = {
answer.hash,
QString::fromStdString(answer.sAnswer).left(150) + (answer.sAnswer.size() > 150 ? "..." : ""),
answer.nVotes,
QString::fromStdString(answer.GetState(coins)),
answer.CanBeVoted(coins),
answer.CanBeSupported(coins),
(answer.CanBeSupported(coins) || fState == DAOFlags::SUPPORTED) && mapSupported.count(answer.hash) ? tr("Supported") : tr("")
};
answers << a;
}
}
bool fSupported = mapSupported.count(consultation.hash);
if (fState == DAOFlags::SUPPORTED || fState == DAOFlags::NIL)
{
if (fSupported)
myVotes << tr("Supported");
}
else if (consultation.IsRange() && nVote != -10000 && nVote != -1)
{
myVotes << QString::number(nVote);
}
if (consultation.IsRange())
{
std::sort(answers.begin(), answers.end(), [](const ConsultationAnswerEntry &a, const ConsultationAnswerEntry &b) {
return a.answer.toInt() < b.answer.toInt();
});
}
else
{
std::sort(answers.begin(), answers.end(), [](const ConsultationAnswerEntry &a, const ConsultationAnswerEntry &b) {
return a.answer.toInt() < b.answer.toInt();
});
}
myVotes.sort();
bool fCanVote = consultation.CanBeVoted();
if (!consultation.IsRange())
{
fCanVote = fState == DAOFlags::ACCEPTED;
for (ConsultationAnswerEntry &a: answers)
{
if (!a.fCanVote)
{
fCanVote = false;
break;
}
}
}
if (consultation.IsAboutConsensusParameter())
{
if (mapConsultationConsensus.count(consultation.nMin) == 0)
{
mapConsultationConsensus[consultation.nMin].consultation = consultation;
mapConsultationConsensus[consultation.nMin].answers = answers;
mapConsultationConsensus[consultation.nMin].myVotes = myVotes;
mapConsultationConsensus[consultation.nMin].fCanVote = fCanVote;
}
else if (mapBlockIndex.count(mapConsultationConsensus[consultation.nMin].consultation.txblockhash))
{
if (pindex->GetBlockTime() > mapBlockIndex[mapConsultationConsensus[consultation.nMin].consultation.txblockhash]->GetBlockTime())
{
mapConsultationConsensus[consultation.nMin].consultation = consultation;
mapConsultationConsensus[consultation.nMin].answers = answers;
mapConsultationConsensus[consultation.nMin].myVotes = myVotes;
mapConsultationConsensus[consultation.nMin].fCanVote = fCanVote;
}
}
}
QString sState = QString::fromStdString(consultation.GetState(chainActive.Tip(), coins)).replace(", ","\n");
ConsultationEntry p = {
it.first,
"#6666ff",
QString::fromStdString(consultation.strDZeel),
answers,
"",
consultation.nVotingCycle,
sState,
fState,
fCanVote,
myVotes,
(uint64_t)mapBlockIndex[consultation.txblockhash]->GetBlockTime(),
consultation.IsRange(),
consultation.nMin,
consultation.nMax,
fState == DAOFlags::SUPPORTED || fState == DAOFlags::NIL
};
switch (fState)
{
case DAOFlags::NIL:
{
p.color = "#ffdd66";
break;
}
case DAOFlags::ACCEPTED:
{
p.color = "#66ff66";
break;
}
case DAOFlags::EXPIRED:
{
p.color = "#ff6666";
break;
}
}
if (consultation.IsAboutConsensusParameter())
continue;
if (fState == DAOFlags::ACCEPTED &&
((nVote == -10000 && consultation.IsRange()) || (!consultation.IsRange() && myVotes.size() == 0)))
nBadgeConsultations++;
if (nFilter != FILTER_ALL)
{
if (nFilter == FILTER_VOTED && nVote == -10000 && myVotes.size() == 0)
continue;
if (nFilter == FILTER_NOT_VOTED && (nVote != -10000 || myVotes.size() > 0))
continue;
}
if (nFilter2 != FILTER2_ALL)
{
if (nFilter2 == FILTER2_IN_PROGRESS && fState != DAOFlags::ACCEPTED)
continue;
if (nFilter2 == FILTER2_FINISHED && fState != DAOFlags::EXPIRED)
continue;
if ((fState == DAOFlags::NIL && nFilter2 != FILTER2_LOOKING_FOR_SUPPORT) ||
(fState != DAOFlags::NIL && nFilter2 == FILTER2_LOOKING_FOR_SUPPORT))
continue;
}
if (fExclude && (fState == DAOFlags::EXPIRED || fState == DAOFlags::PASSED))
continue;
consultationModel << p;
}
std::sort(consultationModel.begin(), consultationModel.end(), [](const ConsultationEntry &a, const ConsultationEntry &b) {
if (a.ts == b.ts)
return a.hash > b.hash;
else
return a.ts > b.ts;
});
deploymentModel.clear();
const Consensus::Params& consensusParams = Params().GetConsensus();
for (unsigned int i = 0; i < Consensus::MAX_VERSION_BITS_DEPLOYMENTS; i++)
{
QString status = "unknown";
Consensus::DeploymentPos id = (Consensus::DeploymentPos)i;
bool fFinished = false;
bool fInProgress = false;
bool nVoted = false;
if (!consensusParams.vDeployments[id].nStartTime)
continue;
std::vector<std::string>& versionBitVotesRejected = mapMultiArgs["-rejectversionbit"];
std::vector<std::string>& versionBitVotesAccepted = mapMultiArgs["-acceptversionbit"];
for (auto& it: versionBitVotesRejected)
{
if (stoi(it) == consensusParams.vDeployments[id].bit)
{
nVoted = true;
break;
}
}
if (!nVoted)
{
for (auto& it: versionBitVotesAccepted)
{
if (stoi(it) == consensusParams.vDeployments[id].bit)
{
nVoted = true;
break;
}
}
}
const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
switch (thresholdState) {
case THRESHOLD_DEFINED: status = "defined"; fFinished = false; fInProgress = false; break;
case THRESHOLD_STARTED: status = "started"; fFinished = false; fInProgress = true; break;
case THRESHOLD_LOCKED_IN: status = "locked in"; fFinished = true; fInProgress = false; break;
case THRESHOLD_ACTIVE: status = "active"; fFinished = true; fInProgress = false; break;
case THRESHOLD_FAILED: status = "failed"; fFinished = true; fInProgress = false; break;
}
if (fInProgress && !nVoted)
nBadgeDeployments++;
if (nFilter != FILTER_ALL)
{
if (nFilter == FILTER_VOTED && !nVoted)
continue;
if (nFilter == FILTER_NOT_VOTED && nVoted)
continue;
}
if (nFilter2 != FILTER2_ALL)
{
if (nFilter2 == FILTER2_IN_PROGRESS && !fInProgress)
continue;
if (nFilter2 == FILTER2_FINISHED && !fFinished)
continue;
}
bool nVote = !IsVersionBitRejected(consensusParams, id);
DeploymentEntry e = {
"#6666ff",
QString::fromStdString(Consensus::sDeploymentsDesc[id]),
status,
status == "started",
nVote,
!nVoted,
consensusParams.vDeployments[id].nStartTime,
consensusParams.vDeployments[id].bit
};
if (status == "started")
{
e.color = "#ffdd66";
}
else if (status == "locked_in")
{
e.color = "#ff66ff";
}
else if (status == "active")
{
e.color = "#66ff66";
}
else if (status == "failed")
{
e.color = "#ff6666";
}
deploymentModel << e;
}
std::sort(deploymentModel.begin(), deploymentModel.end(), [](const DeploymentEntry &a, const DeploymentEntry &b) {
if (a.ts == b.ts)
return a.title > b.title;
else
return a.ts > b.ts;
});
consensusModel.clear();
for (unsigned int i = 0; i < Consensus::MAX_CONSENSUS_PARAMS; i++)
{
Consensus::ConsensusParamsPos id = (Consensus::ConsensusParamsPos)i;
QString status = "set";
ConsultationConsensusEntry consultation;
consultation.consultation.SetNull();
if (mapConsultationConsensus.count(i))
consultation = mapConsultationConsensus[i];
flags fState = consultation.consultation.GetLastState();
bool fHasConsultation = !consultation.consultation.IsNull() && fState != DAOFlags::EXPIRED && fState != DAOFlags::PASSED;
if (fHasConsultation && (fState == DAOFlags::NIL || fState == DAOFlags::SUPPORTED || fState == DAOFlags::REFLECTION))
status = tr("change proposed") + ", " + QString::fromStdString(consultation.consultation.GetState(chainActive.Tip(), coins));
else if (fHasConsultation && fState == DAOFlags::ACCEPTED)
status = tr("voting");
status.replace(", ","\n");
if (fHasConsultation && consultation.myVotes.size() == 0 && fState == DAOFlags::ACCEPTED)
nBadgeConsensus++;
if (nFilter != FILTER_ALL)
{
if (nFilter == FILTER_VOTED && consultation.myVotes.size() == 0)
continue;
if (nFilter == FILTER_NOT_VOTED && consultation.myVotes.size() > 0)
continue;
}
if (nFilter2 != FILTER2_ALL)
{
if (nFilter2 == FILTER2_IN_PROGRESS && !fHasConsultation)
continue;
if (nFilter2 == FILTER2_FINISHED && fHasConsultation)
continue;
}
QVector<ConsultationAnswerEntry> answers;
QStringList myVotes;
ConsensusEntry e = {
fHasConsultation ? consultation.consultation.hash : uint256(),
"#6666ff",
QString::fromStdString(Consensus::sConsensusParamsDesc[id]),
GetConsensusParameter(id, coins),
consultation.answers,
0,
status,
fState,
fHasConsultation && fState == DAOFlags::ACCEPTED,
consultation.myVotes,
fHasConsultation && (fState == DAOFlags::NIL || fState == DAOFlags::SUPPORTED),
Consensus::vConsensusParamsType[id],
i
};
if (status == "started")
{
e.color = "#ffdd66";
}
else if (status == "locked_in")
{
e.color = "#ff66ff";
}
else if (status == "active")
{
e.color = "#66ff66";
}
else if (status == "failed")
{
e.color = "#ff6666";
}
consensusModel << e;
}
if (nCurrentView == VIEW_PROPOSALS)
{
if (updateFilterIfEmpty && proposalModel.size() == 0)
onFilter(FILTER_VOTED);
setData(proposalModel);
}
else if (nCurrentView == VIEW_PAYMENT_REQUESTS)
{
if (updateFilterIfEmpty && paymentRequestModel.size() == 0)
onFilter(FILTER_VOTED);
setData(paymentRequestModel);
}
else if (nCurrentView == VIEW_CONSULTATIONS)
{
if (updateFilterIfEmpty && consultationModel.size() == 0)
onFilter(FILTER_VOTED);
setData(consultationModel);
}
else if (nCurrentView == VIEW_DEPLOYMENTS)
{
if (updateFilterIfEmpty && deploymentModel.size() == 0)
onFilter(FILTER_VOTED);
setData(deploymentModel);
}
else if (nCurrentView == VIEW_CONSENSUS)
{
if (updateFilterIfEmpty && consensusModel.size() == 0)
onFilter(FILTER_VOTED);
setData(consensusModel);
}
proposalsBtn->setBadge(nBadgeProposals);
paymentRequestsBtn->setBadge(nBadgePaymentRequests);
consultationsBtn->setBadge(nBadgeConsultations);
deploymentsBtn->setBadge(nBadgeDeployments);
consensusBtn->setBadge(nBadgeConsensus);
Q_EMIT daoEntriesChanged(nBadgeProposals + nBadgeConsensus + nBadgeConsultations + nBadgeDeployments + nBadgePaymentRequests);
}
void DaoPage::setData(QVector<ProposalEntry> data)
{
table->clearContents();
table->setRowCount(data.count());
table->setSortingEnabled(false);
for (int i = 0; i < data.count(); ++i) {
auto &entry = data[i];
// HASH
auto *hashItem = new QTableWidgetItem;
hashItem->setData(Qt::DisplayRole, QString::fromStdString(entry.hash.GetHex()));
table->setItem(i, P_COLUMN_HASH, hashItem);
// COLOR
auto *colorItem = new QTableWidgetItem;
auto *indicatorBox = new QFrame;
indicatorBox->setContentsMargins(QMargins());
indicatorBox->setStyleSheet(QString("background-color: %1;").arg(entry.color));
indicatorBox->setFixedWidth(3);
table->setCellWidget(i, P_COLUMN_COLOR, indicatorBox);
table->setItem(i, P_COLUMN_COLOR, colorItem);
// TITLE
auto *nameItem = new QTableWidgetItem;
nameItem->setData(Qt::DisplayRole, entry.title);
table->setItem(i, P_COLUMN_TITLE, nameItem);
// AMOUNT
auto *amountItem = new QTableWidgetItem;
amountItem->setData(Qt::DisplayRole, entry.requests);
amountItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, P_COLUMN_REQUESTS, amountItem);
// PAID
auto *paidItem = new QTableWidgetItem;
paidItem->setData(Qt::DisplayRole, entry.paid);
paidItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, P_COLUMN_PAID, paidItem);
// DEADLINE
auto *deadlineItem = new QTableWidgetItem;
deadlineItem->setData(Qt::DisplayRole, entry.deadline);
deadlineItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, P_COLUMN_DURATION, deadlineItem);
// VOTES
auto *votesItem = new QTableWidgetItem;
votesItem->setData(Qt::DisplayRole, QString::number(entry.nVotesYes) + "/" + QString::number(entry.nVotesNo) + "/" + QString::number(entry.nVotesAbs));
votesItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, P_COLUMN_VOTES, votesItem);
// STATE
auto *stateItem = new QTableWidgetItem;
stateItem->setData(Qt::DisplayRole, entry.sState);
stateItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, P_COLUMN_STATE, stateItem);
// MY VOTES
auto *myVotesItem = new QTableWidgetItem;
auto voteText = QString();
if (entry.nMyVote == 0)
{
voteText = tr("Voted No.");
}
else if (entry.nMyVote == 1)
{
voteText = tr("Voted Yes.");
}
else if (entry.nMyVote == -1)
{
voteText = tr("Abstain");
}
else if (entry.fCanVote)
{
voteText = tr("Did not vote.");
}
else
{
voteText = tr("Voting finished.");
}
myVotesItem->setData(Qt::DisplayRole, voteText);
myVotesItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, P_COLUMN_MY_VOTES, myVotesItem);
//VOTE
auto *votedItem = new QTableWidgetItem;
auto *widget = new QWidget();
widget->setContentsMargins(QMargins());
widget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
auto *boxLayout = new QHBoxLayout;
boxLayout->setContentsMargins(QMargins());
boxLayout->setSpacing(0);
widget->setLayout(boxLayout);
// Only show vote button if proposal voting is in progress
if (entry.fCanVote) {
auto *button = new QPushButton;
button->setText(voteText.isEmpty() ? tr("Vote") : tr("Change"));
button->setFixedHeight(40);
button->setProperty("id", QString::fromStdString(entry.hash.GetHex()));
boxLayout->addWidget(button, 0, Qt::AlignCenter);
connect(button, SIGNAL(clicked()), this, SLOT(onVote()));
}
table->setItem(i, P_COLUMN_VOTE, votedItem);
table->setCellWidget(i, P_COLUMN_VOTE, widget);
}
uint64_t nWeight = 0;
if (pwalletMain)
nWeight = pwalletMain->GetStakeWeight();
bool fWeight = nWeight > 0;
if (!fWeight) table->setColumnWidth(P_COLUMN_VOTE, 0);
else table->setColumnWidth(P_COLUMN_VOTE, 150);
table->setColumnHidden(P_COLUMN_VOTE, !fWeight);
table->setSortingEnabled(true);
}
void DaoPage::setData(QVector<PaymentRequestEntry> data)
{
table->clearContents();
table->setRowCount(data.count());
table->setSortingEnabled(false);
for (int i = 0; i < data.count(); ++i) {
auto &entry = data[i];
// HASH
auto *hashItem = new QTableWidgetItem;
hashItem->setData(Qt::DisplayRole, QString::fromStdString(entry.hash.GetHex()));
table->setItem(i, PR_COLUMN_HASH, hashItem);
// COLOR
auto *colorItem = new QTableWidgetItem;
auto *indicatorBox = new QFrame;
indicatorBox->setContentsMargins(QMargins());
indicatorBox->setStyleSheet(QString("background-color: %1;").arg(entry.color));
indicatorBox->setFixedWidth(3);
table->setCellWidget(i, PR_COLUMN_COLOR, indicatorBox);
table->setItem(i, PR_COLUMN_COLOR, colorItem);
// PARENT TITLE
auto *parentNameItem = new QTableWidgetItem;
parentNameItem->setData(Qt::DisplayRole, entry.parentTitle);
table->setItem(i, PR_COLUMN_PARENT_TITLE, parentNameItem);
// TITLE
auto *nameItem = new QTableWidgetItem;
nameItem->setData(Qt::DisplayRole, entry.title);
nameItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, PR_COLUMN_TITLE, nameItem);
// AMOUNT
auto *amountItem = new QTableWidgetItem;
amountItem->setData(Qt::DisplayRole, entry.amount);
amountItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, PR_COLUMN_REQUESTS, amountItem);
// VOTES
auto *votesItem = new QTableWidgetItem;
votesItem->setData(Qt::DisplayRole, QString::number(entry.nVotesYes) + "/" + QString::number(entry.nVotesNo) + "/" + QString::number(entry.nVotesAbs));
votesItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, PR_COLUMN_VOTES, votesItem);
// STATE
auto *stateItem = new QTableWidgetItem;
stateItem->setData(Qt::DisplayRole, entry.sState);
stateItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, PR_COLUMN_STATE, stateItem);
// MY VOTE
auto *myVoteItem = new QTableWidgetItem;
auto voteText = QString();
if (entry.nMyVote == 0)
{
voteText = tr("Voted No.");
}
else if (entry.nMyVote == 1)
{
voteText = tr("Voted Yes.");
}
else if (entry.nMyVote == -1)
{
voteText = tr("Abstain");
}
else if (entry.fCanVote)
{
voteText = tr("Did not vote.");
}
else
{
voteText = tr("Voting finished.");
}
myVoteItem->setData(Qt::DisplayRole, voteText);
myVoteItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, PR_COLUMN_MY_VOTES, myVoteItem);
//VOTE
auto *votedItem = new QTableWidgetItem;
auto *widget = new QWidget();
widget->setContentsMargins(QMargins());
widget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
auto *boxLayout = new QHBoxLayout;
boxLayout->setContentsMargins(QMargins());
boxLayout->setSpacing(0);
widget->setLayout(boxLayout);
// Only show vote button if proposal voting is in progress
if (entry.fCanVote) {
auto *button = new QPushButton;
button->setText(voteText.isEmpty() ? tr("Vote") : tr("Change"));
button->setFixedHeight(40);
button->setProperty("id", QString::fromStdString(entry.hash.GetHex()));
boxLayout->addWidget(button, 0, Qt::AlignCenter);
connect(button, SIGNAL(clicked()), this, SLOT(onVote()));
}
table->setCellWidget(i, PR_COLUMN_VOTE, widget);
table->setItem(i, PR_COLUMN_VOTE, votedItem);
}
uint64_t nWeight = 0;
if (pwalletMain)
nWeight = pwalletMain->GetStakeWeight();
bool fWeight = nWeight > 0;
if (!fWeight) table->setColumnWidth(PR_COLUMN_VOTE, 0);
else table->setColumnWidth(PR_COLUMN_VOTE, 150);
table->setColumnHidden(PR_COLUMN_VOTE, !fWeight);
table->setSortingEnabled(true);
}
void DaoPage::setData(QVector<ConsultationEntry> data)
{
table->clearContents();
table->setRowCount(data.count());
table->setSortingEnabled(false);
for (int i = 0; i < data.count(); ++i) {
ConsultationEntry &entry = data[i];
// HASH
auto *hashItem = new QTableWidgetItem;
hashItem->setData(Qt::DisplayRole, QString::fromStdString(entry.hash.GetHex()));
table->setItem(i, C_COLUMN_HASH, hashItem);
// COLOR
auto *colorItem = new QTableWidgetItem;
auto *indicatorBox = new QFrame;
indicatorBox->setContentsMargins(QMargins());
indicatorBox->setStyleSheet(QString("background-color: %1;").arg(entry.color));
indicatorBox->setFixedWidth(3);
table->setCellWidget(i, C_COLUMN_COLOR, indicatorBox);
table->setItem(i, C_COLUMN_COLOR, colorItem);
// TITLE
auto *titleItem = new QTableWidgetItem;
titleItem->setData(Qt::DisplayRole, entry.question);
table->setItem(i, C_COLUMN_TITLE, titleItem);
// ANSWERS
QString answers;
if(entry.fRange)
{
answers = QString(tr("Between %1 and %2")).arg(QString::number(entry.nMin), QString::number(entry.nMax));
}
else
{
QStringList s;
for (auto& it: entry.answers)
{
s << it.answer;
}
s.sort();
answers = s.join(", ");
}
auto *answersItem = new QTableWidgetItem;
answersItem->setData(Qt::DisplayRole, answers);
answersItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, C_COLUMN_ANSWERS, answersItem);
// STATE
auto *statusItem = new QTableWidgetItem;
statusItem->setData(Qt::DisplayRole, entry.sState);
table->setItem(i, C_COLUMN_STATUS, statusItem);
// MY VOTES
auto *myvotesItem = new QTableWidgetItem;
myvotesItem->setData(Qt::DisplayRole, entry.myVotes.join(", "));
myvotesItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, C_COLUMN_MY_VOTES, myvotesItem);
//VOTE
auto *votedItem = new QTableWidgetItem;
auto *widget = new QWidget();
widget->setContentsMargins(QMargins());
widget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
auto *boxLayout = new QHBoxLayout;
boxLayout->setContentsMargins(QMargins());
boxLayout->setSpacing(0);
widget->setLayout(boxLayout);
// Only show vote button if proposal voting is in progress
if (entry.fCanVote || ((entry.fState == DAOFlags::NIL || entry.fState == DAOFlags::SUPPORTED) && entry.fCanSupport)) {
auto *button = new QPushButton;
if (entry.fCanSupport)
button->setText(entry.myVotes.size() == 0 ? tr("Support") : tr("Unsupport"));
else if(entry.fCanVote)
button->setText(entry.myVotes.size() == 0 ? tr("Vote") : tr("Change"));
button->setFixedHeight(40);
button->setProperty("id", QString::fromStdString(entry.hash.GetHex()));
boxLayout->addWidget(button, 0, Qt::AlignCenter);
connect(button, SIGNAL(clicked()), this, SLOT(onVote()));
}
table->setCellWidget(i, C_COLUMN_VOTE, widget);
table->setItem(i, C_COLUMN_VOTE, votedItem);
}
uint64_t nWeight = 0;
if (pwalletMain)
nWeight = pwalletMain->GetStakeWeight();
bool fWeight = nWeight > 0;
if (!fWeight) {
table->setColumnWidth(C_COLUMN_VOTE, 0);
table->setColumnWidth(C_COLUMN_MY_VOTES, 0);
}
else
{
table->setColumnWidth(C_COLUMN_VOTE, 150);
table->setColumnWidth(C_COLUMN_MY_VOTES, 150);
}
table->setColumnHidden(C_COLUMN_VOTE, !fWeight);
table->setColumnHidden(C_COLUMN_MY_VOTES, !fWeight);
table->setSortingEnabled(true);
}
void DaoPage::setData(QVector<DeploymentEntry> data)
{
table->clearContents();
table->setRowCount(data.count());
table->setSortingEnabled(false);
for (int i = 0; i < data.count(); ++i) {
DeploymentEntry &entry = data[i];
// COLOR
auto *colorItem = new QTableWidgetItem;
auto *indicatorBox = new QFrame;
indicatorBox->setContentsMargins(QMargins());
indicatorBox->setStyleSheet(QString("background-color: %1;").arg(entry.color));
indicatorBox->setFixedWidth(3);
table->setCellWidget(i, D_COLUMN_COLOR, indicatorBox);
table->setItem(i, D_COLUMN_COLOR, colorItem);
// TITLE
auto *titleItem = new QTableWidgetItem;
titleItem->setData(Qt::DisplayRole, entry.title);
table->setItem(i, D_COLUMN_TITLE, titleItem);
// STATE
auto *statusItem = new QTableWidgetItem;
statusItem->setData(Qt::DisplayRole, entry.status);
statusItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, D_COLUMN_STATUS, statusItem);
// MY VOTES
auto *myvotesItem = new QTableWidgetItem;
myvotesItem->setData(Qt::DisplayRole, entry.fMyVote ? tr("Yes") : tr("No"));
myvotesItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, D_COLUMN_MY_VOTES, myvotesItem);
// VOTE
auto *votedItem = new QTableWidgetItem;
auto *widget = new QWidget();
widget->setContentsMargins(QMargins());
widget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
auto *boxLayout = new QHBoxLayout;
boxLayout->setContentsMargins(QMargins());
boxLayout->setSpacing(0);
widget->setLayout(boxLayout);
// Only show vote button if proposal voting is in progress
if (entry.fCanVote) {
auto *button = new QPushButton;
button->setText(tr("Change"));
button->setFixedHeight(40);
button->setProperty("id", entry.bit);
button->setProperty("vote", !entry.fMyVote);
boxLayout->addWidget(button, 0, Qt::AlignCenter);
connect(button, SIGNAL(clicked()), this, SLOT(onVote()));
if (entry.fDefaultVote)
{
auto *buttonConfirm = new QPushButton;
buttonConfirm->setText(tr("Confirm"));
buttonConfirm->setFixedHeight(40);
buttonConfirm->setProperty("id", entry.bit);
buttonConfirm->setProperty("vote", entry.fMyVote);
boxLayout->addWidget(buttonConfirm, 0, Qt::AlignCenter);
connect(buttonConfirm, SIGNAL(clicked()), this, SLOT(onVote()));
}
}
table->setCellWidget(i, D_COLUMN_VOTE, widget);
table->setItem(i, D_COLUMN_VOTE, votedItem);
}
table->setSortingEnabled(true);
}
void DaoPage::setData(QVector<ConsensusEntry> data)
{
table->clearContents();
table->setRowCount(data.count());
table->setSortingEnabled(false);
for (int i = 0; i < data.count(); ++i) {
ConsensusEntry &entry = data[i];
// HASH
auto *hashItem = new QTableWidgetItem;
hashItem->setData(Qt::DisplayRole, QString::fromStdString(entry.hash.GetHex()));
table->setItem(i, CP_COLUMN_HASH, hashItem);
// HASH
auto *idItem = new QTableWidgetItem;
idItem->setData(Qt::DisplayRole, entry.id);
table->setItem(i, CP_COLUMN_ID, idItem);
// COLOR
auto *colorItem = new QTableWidgetItem;
auto *indicatorBox = new QFrame;
indicatorBox->setContentsMargins(QMargins());
indicatorBox->setStyleSheet(QString("background-color: %1;").arg(entry.color));
indicatorBox->setFixedWidth(3);
table->setCellWidget(i, CP_COLUMN_COLOR, indicatorBox);
table->setItem(i, CP_COLUMN_COLOR, colorItem);
// TITLE
auto *titleItem = new QTableWidgetItem;
titleItem->setData(Qt::DisplayRole, entry.parameter);
table->setItem(i, CP_COLUMN_TITLE, titleItem);
// STATE
auto *statusItem = new QTableWidgetItem;
statusItem->setData(Qt::DisplayRole, entry.sState);
statusItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, CP_COLUMN_STATUS, statusItem);
// VALUE
auto *valueItem = new QTableWidgetItem;
QString sValue = QString::number(entry.value);
valueItem->setData(Qt::DisplayRole, QString::fromStdString(FormatConsensusParameter((Consensus::ConsensusParamsPos)entry.id, sValue.toStdString())));
valueItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, CP_COLUMN_CURRENT, valueItem);
// MY VOTES
auto *myvotesItem = new QTableWidgetItem;
myvotesItem->setData(Qt::DisplayRole, entry.myVotes.join(", "));
myvotesItem->setData(Qt::TextAlignmentRole,Qt::AlignCenter);
table->setItem(i, CP_COLUMN_MY_VOTES, myvotesItem);
//VOTE
auto *votedItem = new QTableWidgetItem;
auto *widget = new QWidget();
widget->setContentsMargins(QMargins());
widget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
auto *boxLayout = new QHBoxLayout;
boxLayout->setContentsMargins(QMargins());
boxLayout->setSpacing(0);
widget->setLayout(boxLayout);
// Only show vote button if proposal voting is in progress
if ((entry.fCanVote && entry.fState != DAOFlags::REFLECTION) || ((entry.fState == DAOFlags::NIL || entry.fState == DAOFlags::SUPPORTED) && entry.fCanSupport)) {
auto *button = new QPushButton;
if (entry.fCanSupport)
button->setText(entry.myVotes.size() == 0 ? tr("Support") : tr("Unsupport"));
else if(entry.fCanVote)
button->setText(entry.myVotes.size() == 0 ? tr("Vote") : tr("Change"));
button->setFixedHeight(40);
button->setProperty("id", QString::fromStdString(entry.hash.GetHex()));
boxLayout->addWidget(button, 0, Qt::AlignCenter);
connect(button, SIGNAL(clicked()), this, SLOT(onVote()));
}
table->setCellWidget(i, CP_COLUMN_VOTE, widget);
table->setItem(i, CP_COLUMN_VOTE, votedItem);
}
uint64_t nWeight = 0;
if (pwalletMain)
nWeight = pwalletMain->GetStakeWeight();
bool fWeight = nWeight > 0;
if (!fWeight) {
table->setColumnWidth(CP_COLUMN_VOTE, 0);
table->setColumnWidth(CP_COLUMN_MY_VOTES, 0);
}
else
{
table->setColumnWidth(CP_COLUMN_VOTE, 150);
table->setColumnWidth(CP_COLUMN_MY_VOTES, 150);
}
table->setColumnHidden(CP_COLUMN_VOTE, !fWeight);
table->setColumnHidden(CP_COLUMN_MY_VOTES, !fWeight);
table->setSortingEnabled(true);
}
void DaoPage::onVote() {
LOCK(cs_main);
QVariant idV = sender()->property("id");
QVariant voteV = sender()->property("vote");
CStateViewCache coins(pcoinsTip);
if (idV.isValid() && voteV.isValid())
{
VoteVersionBit(idV.toInt(), voteV.toBool());
}
else if (idV.isValid())
{
CProposal proposal;
CPaymentRequest prequest;
CConsultation consultation;
CConsultationAnswer answer;
uint256 hash = uint256S(idV.toString().toStdString());
if (coins.GetProposal(hash, proposal))
{
CommunityFundDisplayDetailed dlg(this, proposal);
dlg.exec();
}
else if (coins.GetPaymentRequest(hash, prequest))
{
CommunityFundDisplayPaymentRequestDetailed dlg(this, prequest);
dlg.exec();
}
else if (coins.GetConsultation(hash, consultation))
{
auto fState = consultation.GetLastState();
if (fState == DAOFlags::NIL || fState == DAOFlags::SUPPORTED)
{
if (consultation.IsRange())
{
bool duplicate;
if (mapSupported.count(consultation.hash))
RemoveSupport(consultation.hash.ToString());
else
Support(consultation.hash, duplicate);
}
else
{
contextHash = QString::fromStdString(consultation.hash.ToString());
onSupportAnswer();
}
}
else
{
DaoConsultationVote dlg(this, consultation);
dlg.exec();
}
}
else if (coins.GetConsultationAnswer(hash, answer))
{
if (answer.CanBeSupported(coins))
{
bool duplicate;
if (mapSupported.count(answer.hash))
RemoveSupport(answer.hash.ToString());
else
Support(answer.hash, duplicate);
}
}
}
refresh(true, true);
}
void DaoPage::onDetails() {
if (!contextHash.isEmpty())
{
QString type;
if (nCurrentView == VIEW_PROPOSALS)
type = "proposal";
else if (nCurrentView == VIEW_PAYMENT_REQUESTS)
type = "payment-request";
else if (nCurrentView == VIEW_CONSULTATIONS)
type = "consultation";
QString link = "https://www.navexplorer.com/dao/" + type + "/" + contextHash;
QDesktopServices::openUrl(QUrl(link));
}
}
void DaoPage::setActiveSection(QWidget* section)
{
proposalsBtn->setProperty("class", "");
paymentRequestsBtn->setProperty("class", "");
consultationsBtn->setProperty("class", "");
deploymentsBtn->setProperty("class", "");
consensusBtn->setProperty("class", "");
section->setProperty("class", "active");
qApp->setStyleSheet(qApp->styleSheet()); // HACKY
}
void DaoPage::viewProposals() {
setView(VIEW_PROPOSALS);
if (filterHash.isEmpty())
{
if (nBadgeProposals > 0)
{
onFilter(FILTER_NOT_VOTED);
onFilter2(FILTER2_IN_PROGRESS);
}
else
{
onFilter(FILTER_ALL);
onFilter2(FILTER2_ALL);
}
}
setActiveSection(proposalsBtn);
}
void DaoPage::viewPaymentRequests() {
setView(VIEW_PAYMENT_REQUESTS);
if (filterHash.isEmpty())
{
if (nBadgePaymentRequests > 0)
{
onFilter(FILTER_NOT_VOTED);
onFilter2(FILTER2_IN_PROGRESS);
}
else
{
onFilter(FILTER_ALL);
onFilter2(FILTER2_ALL);
}
}
setActiveSection(paymentRequestsBtn);
}
void DaoPage::viewConsultations() {
setView(VIEW_CONSULTATIONS);
if (nBadgeConsultations > 0)
{
onFilter(FILTER_NOT_VOTED);
onFilter2(FILTER2_IN_PROGRESS);
}
else
{
onFilter(FILTER_ALL);
onFilter2(FILTER2_ALL);
}
setActiveSection(consultationsBtn);
}
void DaoPage::viewDeployments() {
setView(VIEW_DEPLOYMENTS);
if (nBadgeDeployments > 0)
{
onFilter(FILTER_NOT_VOTED);
onFilter2(FILTER2_IN_PROGRESS);
}
else
{
onFilter(FILTER_ALL);
onFilter2(FILTER2_ALL);
}
setActiveSection(deploymentsBtn);
}
void DaoPage::viewConsensus() {
setView(VIEW_CONSENSUS);
if (filterHash.isEmpty())
{
if (nBadgeConsensus > 0)
{
onFilter(FILTER_NOT_VOTED);
onFilter2(FILTER2_IN_PROGRESS);
}
else
{
onFilter(FILTER_ALL);
onFilter2(FILTER2_ALL);
}
}
setActiveSection(consensusBtn);
}
void DaoPage::backToFilter() {
filterHash = "";
if (nCurrentView == VIEW_PROPOSALS)
viewPaymentRequests();
else if (nCurrentView == VIEW_PAYMENT_REQUESTS)
viewProposals();
}
void DaoPage::onFilter(int index) {
nFilter = index;
filterCmb->setCurrentIndex(index);
refresh(true);
}
void DaoPage::onFilter2(int index) {
nFilter2 = index;
filter2Cmb->setCurrentIndex(index);
refresh(true);
}
void DaoPage::onExclude(bool fChecked) {
fExclude = fChecked;
refresh(true);
}
void DaoPage::onCreateBtn() {
contextHash = "";
onCreate();
}
void DaoPage::onCreate() {
if (nCurrentView == VIEW_PROPOSALS)
{
CommunityFundCreateProposalDialog dlg(this);
dlg.setModel(walletModel);
dlg.exec();
refresh(true);
}
else if (nCurrentView == VIEW_PAYMENT_REQUESTS)
{
CommunityFundCreatePaymentRequestDialog dlg(this);
dlg.setModel(walletModel);
dlg.exec();
refresh(true);
}
else if (nCurrentView == VIEW_CONSULTATIONS)
{
LOCK(cs_main);
CStateViewCache coins(pcoinsTip);
CConsultation consultation;
if (coins.GetConsultation(uint256S(contextHash.toStdString()), consultation))
{
if (consultation.CanHaveNewAnswers())
{
DaoProposeAnswer dlg(this, consultation, [](QString s)->bool{
return !s.isEmpty();
});
dlg.setModel(walletModel);
dlg.exec();
}
}
else
{
DaoConsultationCreate dlg(this);
dlg.setModel(walletModel);
dlg.exec();
}
refresh(true);
}
else if (nCurrentView == VIEW_CONSENSUS && contextId >= 0)
{
LOCK(cs_main);
CStateViewCache coins(pcoinsTip);
CConsultation consultation;
if (coins.GetConsultation(uint256S(contextHash.toStdString()), consultation))
{
if (consultation.CanHaveNewAnswers())
{
DaoProposeAnswer dlg(this, consultation, [consultation](QString s)->bool{
return IsValidConsensusParameterProposal((Consensus::ConsensusParamsPos)consultation.nMin, RemoveFormatConsensusParameter((Consensus::ConsensusParamsPos)consultation.nMin, s.toStdString()), chainActive.Tip(), *pcoinsTip);
});
dlg.setModel(walletModel);
dlg.exec();
}
}
else
{
DaoConsultationCreate dlg(this, QString::fromStdString(Consensus::sConsensusParamsDesc[(Consensus::ConsensusParamsPos)contextId]), contextId);
dlg.setModel(walletModel);
dlg.exec();
}
refresh(true);
}
}
void DaoPage::onSupportAnswer() {
LOCK(cs_main);
CStateViewCache coins(pcoinsTip);
CConsultation consultation;
if (coins.GetConsultation(uint256S(contextHash.toStdString()), consultation))
{
if (!consultation.IsRange())
{
DaoSupport dlg(this, consultation);
dlg.setModel(walletModel);
dlg.exec();
refresh(true);
}
}
}
void DaoPage::showContextMenu(const QPoint& pt) {
if (nView == VIEW_DEPLOYMENTS)
return;
auto *item = table->itemAt(pt);
contextHash = "";
contextId = -1;
if (!item) {
contextItem = nullptr;
return;
}
contextItem = item;
auto *hashItem = table->item(contextItem->row(), P_COLUMN_HASH);
if (hashItem) {
LOCK(cs_main);
CStateViewCache view(pcoinsTip);
CConsultation consultation;
CProposal proposal;
CPaymentRequest prequest;
contextHash = hashItem->data(Qt::DisplayRole).toString();
if (contextHash == QString::fromStdString(uint256().ToString()))
contextHash = "";
copyHash->setDisabled(contextHash == "");
openExplorerAction->setDisabled(contextHash == "");
openChart->setDisabled(contextHash == "");
contextMenu->removeAction(seeProposalAction);
contextMenu->removeAction(seePaymentRequestsAction);
proposeChange->setDisabled(false);
if (nCurrentView != VIEW_CONSENSUS && view.GetConsultation(uint256S(contextHash.toStdString()), consultation))
{
contextMenu->removeAction(proposeChange);
}
else if (view.GetProposal(uint256S(contextHash.toStdString()), proposal))
{
contextMenu->addAction(seePaymentRequestsAction);
contextMenu->removeAction(seeProposalAction);
contextMenu->removeAction(proposeChange);
}
else if (view.GetPaymentRequest(uint256S(contextHash.toStdString()), prequest))
{
contextMenu->addAction(seeProposalAction);
contextMenu->removeAction(seePaymentRequestsAction);
contextMenu->removeAction(proposeChange);
}
else if (nCurrentView == VIEW_CONSENSUS)
{
contextId = table->item(contextItem->row(), CP_COLUMN_ID)->data(Qt::DisplayRole).toInt();
contextMenu->addAction(proposeChange);
if (view.GetConsultation(uint256S(contextHash.toStdString()), consultation) && !consultation.CanHaveAnswers())
contextMenu->removeAction(proposeChange);
}
else
{
contextMenu->removeAction(proposeChange);
}
}
contextMenu->exec(QCursor::pos());
}
void DaoPage::onCopyHash() {
if (contextHash.isEmpty())
return;
QApplication::clipboard()->setText(contextHash, QClipboard::Clipboard);
}
void DaoPage::onSeePaymentRequests() {
if (contextHash.isEmpty())
return;
filterHash = contextHash;
viewPaymentRequests();
}
void DaoPage::onSeeProposal() {
if (contextHash.isEmpty())
return;
LOCK(cs_main);
CStateViewCache view(pcoinsTip);
CPaymentRequest prequest;
if (view.GetPaymentRequest(uint256S(contextHash.toStdString()), prequest))
{
filterHash = QString::fromStdString(prequest.proposalhash.ToString());
}
viewProposals();
}
void DaoPage::onViewChart() {
if (contextHash.isEmpty())
return;
if (fChartOpen)
{
chartDlg->updateHash(uint256S(contextHash.toStdString()));
chartDlg->show();
chartDlg->raise();
chartDlg->activateWindow();
return;
}
chartDlg = new DaoChart(this, uint256S(contextHash.toStdString()));
connect(chartDlg, SIGNAL(accepted()), this, SLOT(closedChart()));
fChartOpen = true;
chartDlg->show();
}
void DaoPage::closedChart() {
fChartOpen = false;
}
DaoChart::DaoChart(QWidget *parent, uint256 hash) :
layout(new QVBoxLayout),
hash(hash)
{
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
this->setLayout(layout);
this->setStyleSheet("background-color:white;");
this->resize(800, 600);
series = new QtCharts::QPieSeries();
chart = new QtCharts::QChart();
chartView = new QtCharts::QChartView(chart);
titleLabel = new QLabel();
titleLabel->setWordWrap(true);
titleLabel->setStyleSheet("background-color:white;");
titleLabel->setAlignment(Qt::AlignCenter);
chart->addSeries(series);
layout->addWidget(titleLabel);
layout->addWidget(chartView);
updateView();
}
void DaoChart::updateHash(uint256 hash)
{
this->hash = hash;
updateView();
}
void DaoChart::updateView() {
CConsultation consultation;
CProposal proposal;
CPaymentRequest prequest;
std::map<QString, uint64_t> mapVotes;
QString title = "";
QString state = "";
CStateViewCache view(pcoinsTip);
auto nMaxCycles = 0;
auto nVotingLength = GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view);
auto nCurrentCycle = 0;
auto nCurrentBlock = (chainActive.Tip()->nHeight % GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view))+1;
bool fShouldShowCycleInfo = true;
{
LOCK(cs_main);
if (view.GetConsultation(hash, consultation))
{
title = QString::fromStdString(consultation.strDZeel);
state = QString::fromStdString(consultation.GetState(chainActive.Tip(), view));
nMaxCycles = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_VOTING_CYCLES, view);
flags fState = consultation.GetLastState();
CBlockIndex* pblockindex = consultation.GetLastStateBlockIndex();
if (pblockindex)
{
auto nCreated = (unsigned int)(pblockindex->nHeight / nVotingLength);
auto nCurrent = (unsigned int)(chainActive.Tip()->nHeight / nVotingLength);
nCurrentCycle = nCurrent - nCreated;
}
else
{
nCurrentCycle = consultation.nVotingCycle;
}
if (fState == DAOFlags::EXPIRED || fState == DAOFlags::PASSED)
fShouldShowCycleInfo = false;
if (fState == DAOFlags::NIL || fState == DAOFlags::SUPPORTED)
{
nCurrentCycle = consultation.nVotingCycle;
nMaxCycles = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_MAX_SUPPORT_CYCLES, view);
title += " - Showing support";
}
else
{
if (fState == DAOFlags::REFLECTION)
{
nMaxCycles = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_REFLECTION_LENGTH, view);
}
if (consultation.mapVotes.count(VoteFlags::VOTE_ABSTAIN))
mapVotes.insert(make_pair(QString(tr("Abstain") + " (" + QString::number(consultation.mapVotes.at(VoteFlags::VOTE_ABSTAIN)) + ")"), consultation.mapVotes.at(VoteFlags::VOTE_ABSTAIN)));
}
if (consultation.IsRange())
{
if (fState == DAOFlags::NIL || fState == DAOFlags::SUPPORTED)
{
mapVotes.insert(make_pair(tr("Showed support") + " (" + QString::number(consultation.nSupport) + ")", consultation.nSupport));
mapVotes.insert(make_pair(tr("Did not show support") + " (" + QString::number(nCurrentBlock-consultation.nSupport) + ")", nCurrentBlock-consultation.nSupport));
}
else
{
for (auto&it: consultation.mapVotes)
{
if (it.first == -1)
continue;
mapVotes.insert(make_pair(QString::number(it.first) + " (" + QString::number(it.second) + ")", it.second));
}
}
}
else
{
CConsultationAnswerMap consultationAnswerMap;
if (view.GetAllConsultationAnswers(consultationAnswerMap))
{
for (auto&it: consultationAnswerMap)
{
CConsultationAnswer answer = it.second;
flags fAnswerState = answer.GetLastState();
if (answer.parent == consultation.hash)
{
auto fState = consultation.GetLastState();
uint64_t nAmount = (!consultation.IsSupported(view) || fState == DAOFlags::SUPPORTED || fState == DAOFlags::REFLECTION || fState == DAOFlags::NIL) ? answer.nSupport : answer.nVotes;
mapVotes.insert(make_pair(QString::fromStdString(consultation.IsAboutConsensusParameter() ? FormatConsensusParameter((Consensus::ConsensusParamsPos)consultation.nMin, answer.sAnswer) : answer.sAnswer) + " (" + QString::number(nAmount) + ", " + QString::number(nAmount*100/nVotingLength)+ "%)",nAmount));
}
}
}
}
}
else if (view.GetProposal(hash, proposal))
{
nCurrentCycle = proposal.nVotingCycle;
nMaxCycles = GetConsensusParameter(Consensus::CONSENSUS_PARAM_PROPOSAL_MAX_VOTING_CYCLES, view);
title = QString::fromStdString(proposal.strDZeel);
state = QString::fromStdString(proposal.GetState(chainActive.Tip()->GetBlockTime(), view));
auto fState = proposal.GetLastState();
if (fState == DAOFlags::ACCEPTED || fState == DAOFlags::REJECTED || fState == DAOFlags::EXPIRED)
fShouldShowCycleInfo = false;
mapVotes.insert(make_pair(QString("Yes (" + QString::number(proposal.nVotesYes) + ")"), proposal.nVotesYes));
mapVotes.insert(make_pair(QString("No (" + QString::number(proposal.nVotesNo) + ")"), proposal.nVotesNo));
mapVotes.insert(make_pair(QString("Abstain (" + QString::number(proposal.nVotesAbs) + ")"), proposal.nVotesAbs));
}
else if (view.GetPaymentRequest(hash, prequest))
{
nCurrentCycle = prequest.nVotingCycle;
nMaxCycles = GetConsensusParameter(Consensus::CONSENSUS_PARAM_PAYMENT_REQUEST_MAX_VOTING_CYCLES, view);
title = QString::fromStdString(prequest.strDZeel);
state = QString::fromStdString(prequest.GetState(view));
auto fState = prequest.GetLastState();
if (fState == DAOFlags::ACCEPTED || fState == DAOFlags::REJECTED || fState == DAOFlags::EXPIRED || fState == DAOFlags::PAID)
fShouldShowCycleInfo = false;
mapVotes.insert(make_pair(QString("Yes (" + QString::number(prequest.nVotesYes) + ")"), prequest.nVotesYes));
mapVotes.insert(make_pair(QString("No (" + QString::number(prequest.nVotesNo) + ")"), prequest.nVotesNo));
mapVotes.insert(make_pair(QString("Abstain (" + QString::number(prequest.nVotesAbs) + ")"), prequest.nVotesAbs));
}
}
series->clear();
int i = 0;
for (auto& it: mapVotes)
{
if (it.second == 0)
continue;
series->append(it.first, it.second);
QtCharts::QPieSlice *slice = series->slices().at(i);
slice->setLabelVisible();
i++;
}
title += "<br><br>";
if (fShouldShowCycleInfo)
{
title += tr("Block %1 of %2")
.arg(nCurrentBlock)
.arg(GetConsensusParameter(Consensus::CONSENSUS_PARAM_VOTING_CYCLE_LENGTH, view));
title += " / ";
title += tr("Cycle %1 of %2").arg(std::min(nMaxCycles,nCurrentCycle)).arg(nMaxCycles);
}
if (state != "")
{
title += "<br><br>";
title += state;
}
titleLabel->setText(title);
chart->legend()->hide();
chartView->setRenderHint(QPainter::Antialiasing);
}
|
/******************************************************
mqtt based networking
*****************************************************/
#pragma once
namespace Qwerty
{
//sub listener used by Qwerty::Listener
class SubActionListener : public virtual mqtt::iaction_listener
{
public:
SubActionListener(const std::string& name) : mName(name) {}
private:
std::string mName;
void on_failure(const mqtt::token& tok) override;
void on_success(const mqtt::token& tok) override;
};
//Listener for message/IO arrival
//(CallBack functions)
//an instance is owned by Qwerty::NetworkModule
class Listener : public virtual mqtt::callback,
public virtual mqtt::iaction_listener
{
public:
Listener();
bool Init(std::string topicToSubsribe, mqtt::async_client* pCli, mqtt::connect_options* pConnOpts);
private:
static const int cQOS = 1;
static const int cRetryAttemptCount = 5;
mqtt::async_client* m_pRefClient; //reference to MQTT client
mqtt::connect_options* m_pRefConnectionOpt; //reference to connection options
SubActionListener mSubListener; // An action listener to display the result of actions.
int mConnectionRetryCount; // Counter for the number of connection retries
std::string mTopicToSubscribe;
//function pointer to inform that the scene state transfers to another state
//void(*m_pOnRemoteMessageArrivedCallbackFunc)(std::string && msg);
//reconnect if connection is lost
void mFunction_Reconnect();
// Re-connection failure
void on_failure(const mqtt::token& tok) override;
// Re-connection success
void on_success(const mqtt::token& tok) override;
// Callback for when the connection is lost.
// This will initiate the attempt to manually reconnect.
void connection_lost(const std::string& cause) override;
// Callback for when a message arrives.
void message_arrived(mqtt::const_message_ptr msg) override;
void delivery_complete(mqtt::delivery_token_ptr token) override;
};
//Network Transimission module based on MQTT protocol
class NetworkModule
{
public:
NetworkModule();
bool Init(std::string serverAddr, std::string clientId, std::string topic);
bool Connect();
void Send(std::string s);
bool Disconnect();
private:
Listener mMqttListener; //listener to messages/receiver (callback functions)
mqtt::connect_options* m_pConnectionOpt;// Options to use if we need to reconnect
mqtt::async_client* m_pClient;
std::string mServerAddress;
std::string mClientId;
std::string mTopic;
};
}
|
#include <iostream>
using namespace std;
int main()
{
int n,arr[40],count=0,x;
cin>>n>>x;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=0;i<n;i++)
{
if(x==arr[i])
{
count++;
}
}
cout<<"The count is:"<<count<<endl;
return 0;
}
|
#ifndef _MODESHIPVSTOWER_
#define _MODESHIPVSTOWER_
#include "GamePlayDemo.h"
//#include "TypeDef.h"
//#define theModeShipVsTower ModeShipVSTower::getInstance()
class ModeShipVSTower : public GamePlayDemo
{
protected:
// time to survive
float m_fTimeToSurvive;
// time before defeat
float m_fTimeBeforeDefeat;
// this value is used to display message
// when a item is clicked by a user that
// has not bought the item
char* m_sMessagePurchase;
// the variable can be used for the alien team to buid wave
int m_iWave;
// previous wave
int m_iPreviousWave;
// create all button for building tower
// in this version we will use menu otem image
virtual void CreateButtonTower();
// tgis function make the button tower red
// if not availabel
virtual void updateButtonTower(float dt);
// will be called when button marine is clicked
virtual void OnClickButtonMarine(Ref* pSender);
// will be called when button marauder is clicked
virtual void OnClickButtonMarauder(Ref* pSender);
// will be called when button firebat is clicked
virtual void OnClickButtonFireBat(Ref* pSender);
// will be called when button Tank is clicked
virtual void OnClickButtonTank(Ref* pSender);
// will be called when button Thor is clicked
virtual void OnClickButtonThor(Ref* pSender);
// will be called when button marine is clicked
virtual void OnClickButtonHellion(Ref* pSender);
virtual bool onTouchBegan(Touch* touch, Event *event);
virtual void onTouchEnded(Touch* touch, Event *event);
//virtual void onTouchMoved(Touch *touch, Event *event);
// will rack the mouse position
virtual void onMouseMove(Event *pEvent);
// this function Unlock tower and ship when Pack1
// is purchased
virtual void UnLockTowerAndShip();
// this function lock all tower and ship
// relative to purcase of Pack1
virtual void lockTowerAndShip();
// this function will disable button
// relative to tower not unlocked
virtual void disableLockedTower();
// this function will disable button
// relative to tower not unlocked
virtual void enableUnLockedTower();
// add background for tower selection
virtual void addBackGroundForTower();
// create icon for value like mineral,hp,damage
// of the seelcted eleeeent
virtual void createIcon();
// create label for description
virtual void createLabelForIcon();
// update label for descrption
virtual void updateLabelForIcon();
// create label for description
virtual void createLabelForDescription();
// update label for descrption
virtual void updateLabelForDescription();
// display message when tower available
// for build
virtual void displayMessage();
// this function will create button
// for start,restart and exit
virtual void createButtonLayer();
// called when restart game or exit ir
virtual void deleteAll();
// clear the tile id when exit a game
virtual void clearTileId();
// called when game restart or when game is exited and
// entered
virtual void reInitAll();
virtual void onReStart(Ref* pSender);
virtual void onExit(Ref* pSender);
// called when click on button purchase
virtual void onPurchase(Ref* pSender);
// will restart the game
virtual void reStart();
// create the message purchaqe
void createMessagePurchase();
// for time before dead
void updateTimeBeforeDefeat();
void decreaseTimeBuilding(float dt);
// update the ship creation
virtual void updateShipCreation(float dt);
public:
ModeShipVSTower();
~ModeShipVSTower();
// static instance
static ModeShipVSTower* getInstance();
// will create the the tiles and
// set the map to this layer
virtual void createMap();
// will add wall
virtual void addWall(int type, Vec2 pos, Vec2 posTile);
//initialise all team
virtual void addTeam();
// usual suspects
virtual void Start();
virtual void update(float dt);
virtual void Exit();
// this funcipn is used to initalise monster at the beginning
virtual void createShip();
// will create ship that will be on group
// team
virtual void createShip(Team* team);
// if tou uncomment the value DEBUGGAME
// you will create label for debug
virtual void createLabelForDebug();
// if tou uncomment the value DEBUGGAME
// you will create label for debug
virtual void updateLabelForDebug(float dt);
// add projectile given a type of weapon
virtual void addProjectile(BaseEntity* shooter, CCPoint target, int type);
// this function will configute tower
virtual void configTower(Tower* tower, float reali, float realj);
// add a tower on a given position (x,y)
// tileid is the gid that identifies tiles
virtual void addTower(int tileId, float x, float y);
// Victory Condition
virtual bool testVictoryCondition();
// Defeat condition
virtual bool testDefeatCondition();
virtual void addMessageVictorious();
virtual void addMessageDefeat();
virtual void removeMessageCondition();
};
#endif
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "SYCharacter.h"
#include "GameFramework/PlayerController.h"
#include "SYPlayerController.generated.h"
/**
*
*/
UCLASS()
class SYCHARACTER_API ASYPlayerController : public APlayerController
{
GENERATED_BODY()
public:
ASYPlayerController();
//얘들은 왜 필요한건지 모르겠음
virtual void PostInitializeComponents() override;
virtual void OnPossess(APawn* aPawn) override;
protected:
virtual void BeginPlay() override;
};
|
#include "base.hpp"
#include <iostream>
/* hello */
Base::Base() {
std::cout << "Base constructed" << std::endl;
}
|
#include "AnalyticSolver.h"
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
void AnalyticSolver::analyticSolution(matrix &m, int iterations)
{
double x = 0.0;
double y = 0.0;
double x_step = 1.0 / (m.getNumberOfColumns() - 1);
double y_step = 1.0 / (m.getNumberOfRows() - 1);
double tmp;
for(int i = 0; i < m.getNumberOfRows(); i++)
{
x = 0.0;
for(int j = 0; j < m.getNumberOfColumns(); j++)
{
tmp = 0.0;
for(int it = 1; it < iterations; it+=2)
{
tmp += (-8 * sinh(it * M_PI * (1.0-x)) * sin(it * M_PI * y)) / (M_PI * it * (it * it - 4) * sinh(it * M_PI)) ;
}
m.setValue(i, j, tmp);
x += x_step;
}
y += y_step;
}
}
double AnalyticSolver::validate(matrix & m1, matrix & m2)
{
if((m1.getNumberOfColumns() != m2.getNumberOfColumns()) || (m1.getNumberOfRows() != m2.getNumberOfRows())) return -1.0;
srand((time(0)));
double error = 0.0;
for(int i = 0; i < m1.getNumberOfRows(); i++)
{
int c = rand() % m1.getNumberOfColumns();
int r = rand() % m1.getNumberOfRows();
if(fabs(m1(r,c) - m2(r,c)) > error) error = fabs(m1(r,c) - m2(r,c));
}
return error;
}
|
#include "mypushbutton.h"
#include<QPushButton>
#include <QDebug>
#include <QPropertyAnimation>
MyPushButton::MyPushButton(QString normalImg, QString pressImg)
{
normalImgPath = normalImg;
pressedImgPath = pressImg;
QPixmap pixmap;
bool ret = pixmap.load(normalImgPath);
if(!ret)
{
qDebug() << normalImg << "加载图片失效" << endl;
}
this->setFixedSize(pixmap.width(), pixmap.height());
// 设置不规则图片的样式表
this->setStyleSheet("QPushButton{border:Opx;}");
this->setIcon(pixmap);
this->setIconSize(QSize(pixmap.width(), pixmap.height()));
}
void MyPushButton::zoom1()
{
QPropertyAnimation *animation1 = new QPropertyAnimation(this, "geometry");
animation1->setDuration(200);
// 设置初始位置
animation1->setStartValue(QRect(this->x(), this->y(),this->width(),this->height()));
// 设置末位置
animation1->setEndValue(QRect(this->x(), this->y()+10,this->width(),this->height()));
// 设置缓和曲线
animation1->setEasingCurve(QEasingCurve::OutBounce);
// 开始执行动漫
animation1->start();
}
void MyPushButton::zoom2()
{
QPropertyAnimation *animation1 = new QPropertyAnimation(this, "geometry");
animation1->setDuration(200);
animation1->setStartValue(QRect(this->x(), this->y()+10, this->width(), this->height()));
animation1->setEndValue(QRect(this->x(), this->y(), this->width(), this->height()));
animation1->setEasingCurve(QEasingCurve::OutBounce);
animation1->start();
}
void MyPushButton::mousePressEvent(QMouseEvent *e)
{
if(pressedImgPath != "")
{
QPixmap pixmap;
bool ret = pixmap.load(pressedImgPath);
if(!ret)
{
qDebug() << pressedImgPath << "加载图片失败" << endl;
}
this->setFixedSize(pixmap.width(),pixmap.height());
this->setStyleSheet("QPushButton{border:Opx;}");
this->setIcon(pixmap);
this->setIconSize(QSize(pixmap.width(), pixmap.height()));
}
QPushButton::mousePressEvent(e);
}
void MyPushButton::mouseReleaseEvent(QMouseEvent *e)
{
if(normalImgPath != "")
{
QPixmap pixmap;
bool ret = pixmap.load(normalImgPath);
if(!ret)
{
qDebug() << normalImgPath << "加载图片失败" << endl;
}
this->setFixedSize(pixmap.width(),pixmap.height());
this->setStyleSheet("QPushButton{border:Opx;}");
this->setIcon(pixmap);
this->setIconSize(QSize(pixmap.width(), pixmap.height()));
}
QPushButton::mouseReleaseEvent(e);
}
|
#include <cstdio>
#include <queue>
#define rep(x,n) for(x=n;x<13;x++)
using namespace std;
bool judge(int a[]){
queue<int> q;
q.push(a[0]);
int c=0,find[20]={0};
for(int i=0;i<5;i++){
find[a[i]]=1;
}
if(a[0]==3&&a[1]==6&&a[2]==7&&a[3]==8&&a[4]==11){
printf("test\n");
}
int vis[20]={0};
vis[a[0]]=1;
while(!q.empty()){
int t=q.front();
//printf("%d\n",t);
q.pop();
c++;
if(t-1>0&&vis[t-1]!=1&&find[t-1]&&t!=5&&t!=9){
vis[t-1]=1;
q.push(t-1);
}
if(t-4>0&&vis[t-4]!=1&&find[t-4]){
vis[t-4]=1;
q.push(t-4);
}
if(t+1<12&&vis[t+1]!=1&&find[t+1]&&(t!=4&&t!=8))
{
vis[t+1]=1;
q.push(t+1);
}
if(t+4<12&&vis[t+4]!=1&&find[t+4]){
vis[t+4]=1;
q.push(t+4);
}
}
if(c==5)return true;
return false;
}
int main(){
int a[6],count=0;
rep(a[0],1)rep(a[1],a[0])rep(a[2],a[1])rep(a[3],a[2])rep(a[4],a[3]){
//rep(a[0],1)rep(a[1],1)rep(a[2],1)rep(a[3],1)rep(a[4],1){
if(a[0]==a[1]||a[0]==a[2]||a[0]==a[3]||a[0]==a[4]||a[1]==a[2]||a[1]==a[3]||a[1]==a[4]||a[2]==a[3]||a[2]==a[4]||a[3]==a[4])
continue;
if(judge(a)){
int find[20]={0};
for(int i=0;i<5;i++){
find[a[i]]=1;
}
printf("Case%d:\n",count+1);
for(int i=1;i<=3;i++){
for(int j=1;j<5;j++){
if(find[(i-1)*4+j])printf("%3c",'*');
else printf("%3d",(i-1)*4+j);
}
printf("\n");
}
count++;
}
//printf("%d %d %d %d %d\n",a[0],a[1],a[2],a[3],a[4]);
}
printf("count:%d\n",count);
return 0;
}
/*
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int a[12]= {1,2,3,4,6,7,8,9,11,12,13,14},vis[20];
int main()
{
int sum=0;
for(int i1=0; i1<12; i1++)
for(int i2=i1+1; i2<12; i2++)
for(int i3=i2+1; i3<12; i3++)
for(int i4=i3+1; i4<12; i4++)
for(int i5=i4+1; i5<12; i5++)
{
memset (vis,0,sizeof(vis));
int p=0;
vis[a[i1]]=1;
vis[a[i2]]=1;
vis[a[i3]]=1;
vis[a[i4]]=1;
vis[a[i5]]=1;
queue<int>q;
q.push(a[i1]);
vis[a[i1]]=0;
while(!q.empty())
{
int top=q.front();
q.pop();
p++;
if(vis[top+1]) { q.push(top+1);vis[top+1]=0; }
if(vis[top+5]) { q.push(top+5);vis[top+5]=0; }
if(vis[top-1]) { q.push(top-1);vis[top-1]=0; }
if(vis[top-5]) { q.push(top-5);vis[top-5]=0; }
}
if(p==5)
{
sum++;
cout<<a[i1]<<" "<<a[i2]<<" "<<a[i3]<<" "<<a[i4]<<" "<<a[i5]<<endl;
}
}
cout<<sum<<endl;
return 0;
}
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.