text
stringlengths 8
6.88M
|
|---|
//---------------------------------------------------------
//
// Project: dada
// Module: gl
// File: VBO.h
// Author: Viacheslav Pryshchepa
//
// Description:
//
//---------------------------------------------------------
#pragma once
#include "dada/core/Object.h"
namespace dada
{
class VBO : public Object
{
public:
DADA_OBJECT(VBO, Object)
typedef unsigned int id_t;
public:
VBO();
~VBO();
bool isInited() const;
id_t getID() const;
bool bind();
bool load(unsigned int size, const void* data);
private:
id_t m_id;
};
inline bool VBO::isInited() const
{
return m_id != 0;
}
inline VBO::id_t VBO::getID() const
{
return m_id;
}
} // dada
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. 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)
*/
#ifndef NULL_WIDGET_H
#define NULL_WIDGET_H
#include "adjunct/quick_toolkit/widgets/QuickWidget.h"
/** @brief An empty widget
*/
class NullWidget : public QuickWidget
{
IMPLEMENT_TYPEDOBJECT(QuickWidget);
public:
OP_STATUS Init() { return OpStatus::OK; }
virtual unsigned GetDefaultMinimumWidth() { return 0; }
virtual unsigned GetDefaultMinimumHeight(unsigned width) { return 0; }
virtual unsigned GetDefaultPreferredWidth() { return 0; }
virtual unsigned GetDefaultPreferredHeight(unsigned width) { return 0; }
virtual unsigned GetDefaultNominalWidth() { return 0; }
virtual unsigned GetDefaultNominalHeight(unsigned width) { return 0; }
virtual void GetDefaultMargins(WidgetSizes::Margins& margins) {}
virtual unsigned GetDefaultVerticalMargin() { return 0; }
virtual BOOL HeightDependsOnWidth() { return FALSE; }
virtual OP_STATUS Layout(const OpRect& rect) { return OpStatus::OK; }
virtual void SetParentOpWidget(class OpWidget* parent) {}
virtual void Show() { }
virtual void Hide() { }
virtual BOOL IsVisible() { return TRUE; }
virtual void SetEnabled(BOOL enabled) { }
};
#endif // NULL_WIDGET_H
|
#ifndef JSONPARSE_H
#define JSONPARSE_H
#include <iostream>
#include <jsoncpp/json.h>
using namespace std;
int jsonParse(string _s);
#endif /* JSONPARSE_H */
|
#include "class_int.h"
cint::cint()
{
size=0;
int_=NULL;
}
cint::cint(int s_int)
{
size=1;
int_=(int*)malloc( sizeof(int));
int_[0]=s_int;
}
cint::~cint()
{
if(int_) free(int_);
}
int& cint::operator[](int index)
{
return int_[index];
}
int cint::length(void)
{
return size;
}
void cint::append(int s_int)
{
reserve(size + 1);
int_[size-1]=s_int;
}
void cint::erase(int pos, int _size)
{
if(_size<0) _size = size-pos;
_size = min( (int)size-pos, _size);
memset(int_+pos*sizeof(int), 0, _size*sizeof(int));
memmove(&int_[pos], &int_[(pos+_size)], (size-_size)*sizeof(int));
unsigned int new_size = size - _size;
memrealloc(new_size);
}
void cint::insert(int pos, int s_int)
{
pos = min(pos, (int)size);
unsigned int old_size = size;
reserve(size+1);
memmove(&int_[(pos+1)], &int_[pos], (old_size-pos)*sizeof(int));
int_[pos]=s_int;
}
void cint::reserve(int _size)
{
if(_size>(int)size){
size = _size;
int_=(int*)realloc(int_, size*sizeof(int));
}
}
void cint::memrealloc(int _size)
{
if(_size!=(int)size){
size = _size;
int_=(int*)realloc(int_, size*sizeof(int));
}
}
|
#ifndef _LINK_H
#define _LINK_H
#include<fstream>
#include<cstdlib>
#include<iostream>
template <class T>
struct box{
T carid;
box<T>*next;
};
template<class T>
class linklist{
protected:
box<T> *head;
box<T> *tails;
int count;
public:
void initialize();
void print();
void printID();
int lenght()const;
bool search(const T& searchItem);
void showspecific(const T& searchItem);
void showsummarise();
linklist();
};
template<class T>
linklist<T>::linklist(){
head = NULL;
tails= NULL;
count = 0;
}
template<class T>
void linklist<T>::initialize(){
box<T>*temporary;
while(head!=NULL){
temporary=head;
head=head->next;
delete temporary;
}
tails = NULL;
count = 0;
}
template<class T>
void linklist<T>::print(){
box<T>*tracker;
tracker = head;
//system("cls");
while(tracker!=NULL)
{
std::cout <<"========================================================\n"
<<"Engine ID = " << tracker->carid.id << std::endl
<< "Model = " << tracker->carid.models << std::endl
<< "Color = " << tracker->carid.color << std::endl
<< "Speed = " << tracker->carid.speed << std::endl
<< "______________________________________________\n"
<< "Price:" << std::endl
<< "Selling = " << tracker->carid.sellprice << std::endl
<< "Retail = " << tracker->carid.retailprice << std::endl
<< "On The Road= " << tracker->carid.oTRprice << std::endl
<< "Sales = " << tracker->carid.totalSales << std::endl
<<"========================================================\n";
tracker=tracker->next;
}
}
template<class T>
void linklist<T>::printID()
{
int index=1;
box<T>*tracker;
tracker = head;
std::cout<< "+++++++++++++++Car Engine ID++++++++++++++++++++\n";
while(tracker!=NULL)
{
std::cout << index<<". " << tracker->carid.id <<"\t"<< tracker->carid.models <<std::endl;
tracker=tracker->next;
index++;
}
std::cout<<"++++++++++++++++++++++++++++++++++++++++++++++++++\n";
std::cout<< "total car: " << lenght() << std::endl;
}
template<class T>
int linklist<T>::lenght()const{
return count;
}
template<class T>
bool linklist<T>::search(const T& searchItem){
box<T>*tracker;
tracker=head;
bool found = false;
while(tracker != NULL && !found)
{
if(tracker->carid == searchItem)
{
found = true;
}
else{
tracker=tracker->next;
}
}
return found;
}
template <class T>
void linklist<T>::showspecific(const T& searchItem){
box<T>*tracker;
tracker=head;
bool found = false;
while(tracker != NULL && !found)
{
if(tracker->carid.id == searchItem.id)
{
found = true;
std::cout <<"========================================================\n"
<<"Engine ID = " << tracker->carid.id << std::endl
<< "Model = " << tracker->carid.models << std::endl
<< "Color = " << tracker->carid.color << std::endl
<< "Speed = " << tracker->carid.speed << std::endl
<< "______________________________________________\n"
<< "Price:" << std::endl
<< "Selling = " << tracker->carid.sellprice << std::endl
<< "Retail = " << tracker->carid.retailprice << std::endl
<< "On The Road= " << tracker->carid.oTRprice << std::endl
<< "Sales = " << tracker->carid.totalSales << std::endl
<<"========================================================\n";
}
else{
tracker=tracker->next;
}
}
if( !found)
{
std::cout << "Item not in the list\n";
//system("pause");
}
}
template <class T>
void linklist<T>::showsummarise(){
box<T>*current;
int cc1=0,cc2=0,cc3=0;
current= this->head;
while(current!=NULL)
{
if(current->carid.speed < 1500)
{
cc1++;
}
else if(current->carid.speed >=1500 && current->carid.speed <= 1799)
{
cc2++;
}
else if(current->carid.speed >=1800)
{
cc3++;
}
current=current->next;
}
std::cout << "Car Information\n"
<<"**************************************\n"
<<"Displacement(cc) Number of Cars \n"
<<"Below 1500 " << cc1 << std::endl
<<"1500 -> 1799 " << cc2 << std::endl
<<"Above 1800 " << cc3 << std::endl
<<"***************************************\n";
}
#endif
|
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <iomanip>
#include <set>
#include <climits>
#include <ctime>
#include <complex>
#include <cmath>
#include <string>
#include <cctype>
#include <cstring>
#include <algorithm>
using namespace std;
#define endl '\n'
typedef pair<int,int> pii;
typedef long double ld;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
const int maxn=200005;
const int INF=0x3f3f3f3f;
const double pi=acos(-1.0);
const double eps=1e-9;
inline int sgn(double a) {
return a<-eps? -1:a>eps;
}
int n,k;
vector<pii> p;
vector<int> ans;
bool cmp(pii a,pii b){
if(a.first==b.first)
return a.second>b.second;
return a.first<b.first;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
cin>>n>>k;
for(int i=0; i<n; i++) {
int t1,t2;
cin>>t1>>t2;
p.push_back(make_pair(t1,1));
p.push_back(make_pair(t2,0));
}
sort(p.begin(),p.end(),cmp);
int cnt=0;
for(int i=0; i<p.size(); i++) {
// cout<<p[i].first<<' '<<p[i].second<<endl;
if(p[i].second) {
cnt++;
if(cnt==k)
ans.push_back(p[i].first);
} else {
if(cnt==k)
ans.push_back(p[i].first);
cnt--;
}
}
cout<<ans.size()/2<<endl;
for(int i=0;i<ans.size();i+=2){
cout<<ans[i]<<' '<<ans[i+1]<<endl;
}
return 0;
}
|
class ItemStone
{
weight = 10;
};
class ItemConcreteBlock
{
weight = 15;
};
class CinderBlocks
{
weight = 100;
};
class MortarBucket
{
weight = 21;
};
class equip_brick
{
weight = 0.5;
};
class CementBag
{
weight = 40;
};
|
#ifndef MEMORY_MODEL_H
#define MEMORY_MODEL_H
#include <stdint.h>
#include <vector>
#include <string>
class MemoryModel
{
public:
MemoryModel();
~MemoryModel();
bool load(const std::string &filename);
private:
std::vector<uint32_t> memory_;
uint64_t start_address_;
uint64_t end_address_;
uint64_t entry_address_;
};
#endif
|
/** Kabuki SDK
@file /.../Source/Kabuki_SDK-Impl/_G/Char.h
@author Cale McCollough
@copyright CopYright 2016 Cale McCollough ©
@license Read accompanying /.../README.md or online at http://www.boost.org/LICENSE_1_0.txt
*/
#pragma once
#include "Color.h"
namespace _G {
/** */
class _G_API Colormap : Image
{
public:
bool isLoaded;
int bpp;
Color_i* colorMap;
Colormap ();
void Create (int Width, int Height, Color_i BGColor);
void Update ();
Color GetPixel (int X, int Y);
bool SetPixel (int X, int Y, Color AColor);
void Draw (Cell& C);
void Draw (Cell& C, int leftEdge, int topEdge);
//bool LoadGLTexture ();
}
}
|
//
// CompleteBinaryTree.hpp
// DataStructures
//
// Created by Tri Khuu on 2/5/18.
// Copyright © 2018 TK. All rights reserved.
//
#ifndef CompleteBinaryTree_hpp
#define CompleteBinaryTree_hpp
#include <vector>
namespace CompleteBinaryTree {
template<typename T>
class AbsCompleteBinaryTree
{
std::vector<T> _items;
unsigned long _heap_size;
protected:
AbsCompleteBinaryTree<T>();
virtual ~AbsCompleteBinaryTree<T>();
const T GetItem(unsigned int) const;
const T GetLastItem() const;
void SetItem(unsigned int, const T);
void EraseLastItem();
void AddItem(const T);
virtual void Swap(unsigned int, unsigned int);
virtual unsigned int GetLeftChildIndex(unsigned int&) const;
virtual unsigned int GetRightChildIndex(unsigned int&) const;
virtual unsigned int GetParentIndex(unsigned int&) const;
virtual bool HasLeftChild(unsigned int&) const;
virtual bool HasRightChild(unsigned int&) const;
virtual bool HasParent(unsigned int&) const;
public:
virtual unsigned long Size() const;
};
};
#endif /* CompleteBinaryTree_hpp */
|
/******<CODE NEVER DIE>******/
#include<bits/stdc++.h>
#include<unordered_map>
using namespace std;
#define ll long long
#define FastIO ios_base::sync_with_stdio(0)
#define IN cin.tie(0)
#define OUT cout.tie(0)
#define CIG cin.ignore()
#define pb push_back
#define pa pair<int,int>
#define f first
#define s second
#define FOR(i,n,m) for(int i=n;i<=m;i++)
#define FORD(i,n,m) for(int i=m;i>=n;i--)
#define reset(A) memset(A,0,sizeof(A))
#define FILEIN freopen("inputDTL.txt","r",stdin)
#define FILEOUT freopen("outputDTL.txt","w",stdout)
/**********DTL**********/
long long const mod=1e9+7;
int const MAX=1e5+5;
/**********DTL**********/
/**********DTL**********/
int Solution(bool a[], bool b[], int n){
int x[n];
FOR(i,0,n-1){
x[i]=a[i]-b[i];
}
unordered_map<int, int> hm;
int sum=0;
int max_len=0;
FOR(i,0,n-1){
sum+=x[i];
if(sum==0){
max_len=i+1;
}
if(hm.find(sum)!=hm.end()){
max_len=max(max_len,i-hm[sum]);
}else{
hm[sum]=i;
}
}
return max_len;
}
/**********main function**********/
int main(){
FastIO; IN; OUT;
int test;
cin >> test;
while(test--){
int n;
cin >> n;
bool a[n+5];
bool b[n+5];
FOR(i,0,n-1){
cin >> a[i];
}
FOR(i,0,n-1){
cin >> b[i];
}
cout << Solution(a,b,n) << endl;
}
return 0;
}
|
#include <IterativeRobot.h>
#include <Joystick.h>
#include <LiveWindow/LiveWindow.h>
#include <RobotDrive.h>
#include <Timer.h>
#include <XboxController.h>
#include <Spark.h>
//^^^^^ All libraries go here ^^^^^\\
double RStick;
double LStick;
int FRP = 3;
int FLP = 2;
int BRP = 0;
int BLP = 1;
//^^^^^ Declare all global variables here ^^^^^\\
class Robot: public frc::IterativeRobot {
public:
Robot() {
myRobot.SetExpiration(0.1);
timer.Start();
}
private:
frc::RobotDrive myRobot { 0, 1, 2, 3}; // Robot drive system uses ports 0-3
frc::XboxController WExbox{0}; //Xbox controller is named WExbox and it goes in port 0
frc::Spark FR{FRP}; //Declare FR as the Spark controlling the FRP
frc::Spark FL{FLP}; //Declare FL as the Spark controlling the FLP
frc::Spark BL{BLP}; //Declare BL as the Spark controlling the BLP
frc::Spark BR{BRP}; //declare BR as the spark controlling the BRP
frc::LiveWindow* lw = frc::LiveWindow::GetInstance();
frc::Timer timer;
void AutonomousInit() override {
timer.Reset(); //Set timer to 0
timer.Start(); //Start timer
}
void AutonomousPeriodic() override {
if (timer.Get() < 5.0)// Drive for 5 seconds
{
myRobot.Drive(-0.5, 0.0); // Drive forwards half speed (this is stock, we need to test it.)
} else {
myRobot.Drive(0.0, 0.0); // Stop robot
}
}
void TeleopInit() override {
//don't need to worry about this yet
}
void TeleopPeriodic() override {
LStick = WExbox.GetY((frc::GenericHID::JoystickHand)0); //check y value of left stick, assign to variable LStick
RStick = WExbox.GetY((frc::GenericHID::JoystickHand)1); //check y value of right stick, assign to variable RStick
FR.Set(RStick); //set Front right spark to right stick
BR.Set(RStick); //set Back right spark to right stick
FL.Set(LStick); //set front left spark to left stick
BL.Set(LStick); //set back left spark to left stick
}
void TestPeriodic() override {
lw->Run();//dont worry about it
}
};
START_ROBOT_CLASS(Robot)
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.empty() || inorder.empty() || preorder.size() != inorder.size()) return NULL;
return rebuild(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode* rebuild(vector<int> &preorder,int preL,int preR,vector<int> &inorder,int inL,int inR){
if(preL > preR || inL > inR) return NULL;
TreeNode *root = new TreeNode(preorder[preL]);
int idx;
for(idx=inL; idx<=inR; ++idx){
if(inorder[idx] == preorder[preL]) break;
}
int leftLen = idx-inL;
int rightLen = inR-idx;
root->left = rebuild(preorder,preL+1,preL+leftLen,inorder,inL,idx-1);
root->right = rebuild(preorder,preR-rightLen+1,preR,inorder,idx+1,inR);
return root;
}
};
|
//===========================================================================
//! @file light_manager.h
//! @brife ライトの管理
//===========================================================================
#pragma once
//===========================================================================
//! @class LightManager
//===========================================================================
class LightManager : ManagerBase
{
public:
//-----------------------------------------------------------------------
//! @name 初期化
//-----------------------------------------------------------------------
//@{
//! @brief コンストラクタ
LightManager() = default;
//! @brief デストラクタ
~LightManager() override = default;
//@}
//-----------------------------------------------------------------------
//! @name タスク
//-----------------------------------------------------------------------
//@{
//-----------------------------------------------------------------------
//! @brief 初期化
//! @return true 正常終了
//! @return false エラー終了
//-----------------------------------------------------------------------
bool initialize() override;
//! @brief 更新
void update() override;
//-----------------------------------------------------------------------
//! @brief 描画(描画モード指定)
//! @param [in] renderMode 描画したいモード
//-----------------------------------------------------------------------
void render(RenderMode renderMode) override;
//! @brief 解放
void cleanup() override;
//! @brief 追加されている光源の定数バッファ更新
void cbUpdateLights();
//! @brief ImGuiのウィンドウを表示
void showImGuiWindow();
private:
//-----------------------------------------------------------------------v
//! @brief ライト削除
//! @param [in] lightType 削除したいライトタイプ
//! @param [in] index 削除したいライトの配列番号
//-----------------------------------------------------------------------
void removeLight(LightType lightType, s32 index);
//@}
private:
//-----------------------------------------------------------------------
//! @name ライトの定数バッファ更新
//-----------------------------------------------------------------------
//@{
//! @brief 平行光源定数バッファ更新
void directionalLightTransferConstantBuffer();
//! @brief 点光源定数バッファ更新
void pointLightTransferConstantBuffer();
//! @brief スポットライト定数バッファ更新
void spotLightTransferConstantBuffer();
//@}
public:
//-----------------------------------------------------------------------
//! 追加
//-----------------------------------------------------------------------
//@{
//-----------------------------------------------------------------------
//! @brief ライト追加(平行光源)
//! @param [in] position 位置
//! @param [in] lookAt 注視点
//! @param [in] color 色
//! @param [in] intensity 強度
//! @return true 正常終了
//! @return false エラー終了
//-----------------------------------------------------------------------
bool addLight(const Vector3& position, const Vector3& lookAt, const Vector4& color, f32 intensity = 1.0f);
//-----------------------------------------------------------------------
//! @brief ライト追加(点光源)
//! @param [in] position 位置
//! @param [in] color 色
//! @param [in] intensity 強度
//! @return true 正常終了
//! @return false エラー終了
//-----------------------------------------------------------------------
bool addLight(const Vector3& position, const Vector4& color, f32 intensity = 1.0f);
//-----------------------------------------------------------------------
//! @brief ライト追加(スポットライト)
//! @param [in] position 位置
//! @param [in] lookAt 注視点
//! @param [in] color 色
//! @param [in] intensity 強度
//! @return true 正常終了
//! @return false エラー終了
//-----------------------------------------------------------------------
bool addSLight(const Vector3& position, const Vector3& lookAt, const Vector4& color, f32 intensity = 1.0f);
//@}
//-----------------------------------------------------------------------
//! 取得
//-----------------------------------------------------------------------
//@{
//-----------------------------------------------------------------------
//! @brief 平行光源取得
//! @return 平行光源のポインタ
//-----------------------------------------------------------------------
DirectionalLight* getDirectionalLight() const;
//template<typename T>
Light* getLight(LightType lightType, u32 index) const;
//@}
private:
std::unique_ptr<KeyInput> inputKey_; //!< キー入力用
// ライト本体
std::unique_ptr<DirectionalLight> directionalLight_; //!< 平行光源
std::vector<std::unique_ptr<PointLight>> pointLights_; //!< 点光源
std::vector<std::unique_ptr<SpotLight>> spotLights_; //!< スポットライト
// 定数バッファ
gpu::ConstantBuffer<cbDirectionalLight> cbDirectionalLight_; //!< 平行光源
gpu::ConstantBuffer<cbPointLight> cbPointLight_; //!< 点光源
gpu::ConstantBuffer<cbSpotLight> cbSpotLight_; //!< スポットライト
// GPUスロット番号
s32 slotDirectional_ = 4;
s32 slotPoint_ = 5;
s32 slotSpot_ = 6;
// 更新フラグ
bool isDirectionalLight_ = true;
bool isPointLight_ = true;
bool isSpotLight_ = true;
// 追加フラグ
//bool addDirectionalLight_ = false;
bool addPointLight_ = false;
bool addSpotLight_ = false;
};
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class BlockTower
{
public:
int getSum(vector<int> &tower)
{
int sum=0;
for (int i=0; i<tower.size(); ++i) {
sum += tower.at(i);
}
return sum;
}
int getTallest(vector <int> blockHeights)
{
int max = 0,sum;
int point = 0,cnt = 0;
bool isContinue = true;
vector<int> tower;
vector<int>::iterator start = blockHeights.begin(),end = blockHeights.end(),oddStart;
while(isContinue){
isContinue = false;
oddStart = end;
// push even
for (vector<int>::iterator it = start; it != end; ++it) {
if((*it)%2 != 0) {
if(point == cnt) {
isContinue = true;
oddStart = it;
break;
}
++cnt;
}
else {
tower.push_back(*it);
}
}
// push odd
for (vector<int>::iterator it = oddStart; it != end; ++it) {
if((*it)%2 != 0) {
tower.push_back(*it);
}
}
++point; cnt = 0;
sum = getSum(tower);
tower.clear();
if(max < sum){
max = sum;
}
}
return max;
}
};
|
/*********************************************************************************************
cfglp : A CFG Language Processor
--------------------------------
About:
Implemented by Tanu Kanvar (tanu@cse.iitb.ac.in) and Uday
Khedker (http://www.cse.iitb.ac.in/~uday) for the courses
cs302+cs306: Language Processors (theory and lab) at IIT
Bombay.
Release date Jan 15, 2013. Copyrights reserved by Uday
Khedker. This implemenation has been made available purely
for academic purposes without any warranty of any kind.
Documentation (functionality, manual, and design) and related
tools are available at http://www.cse.iitb.ac.in/~uday/cfglp
***********************************************************************************************/
#include<string>
#include<fstream>
#include<iostream>
using namespace std;
#include"common-classes.hh"
#include"error-display.hh"
#include"user-options.hh"
#include"local-environment.hh"
#include"icode.hh"
#include"reg-alloc.hh"
#include"symbol-table.hh"
#include"ast.hh"
#include"basic-block.hh"
#include"procedure.hh"
#include"program.hh"
Procedure::Procedure(Data_Type proc_return_type, string proc_name,Argument_Table & argument_list, int line)
{
return_type = proc_return_type;
argument_symbol_table = argument_list;
argument_symbol_table.set_table_scope(local);
name = proc_name;
lineno = line;
return_flag = 0;
}
Procedure::~Procedure()
{
list<Basic_Block *>::iterator i;
for (i = basic_block_list.begin(); i != basic_block_list.end(); i++)
delete (*i);
}
void Procedure::check_valid_bb(){
list<int>::iterator i;
for(i = basic_block_gotos.begin(); i != basic_block_gotos.end(); i++){
if((*i) > (basic_block_list.size() + 1)){
char buff[20];
sprintf(buff, "bb %d does not exist", (*i));
CHECK_INVARIANT(false,buff);
}
}
}
void Procedure::set_return_flag(int ret){
return_flag = ret;
}
int Procedure::get_return_flag(){
return return_flag;
}
string Procedure::get_proc_name()
{
return name;
}
void Procedure::set_basic_block_list(list<Basic_Block *> & bb_list)
{
basic_block_list = bb_list;
}
void Procedure::set_local_list(Symbol_Table & new_list)
{
local_symbol_table = new_list;
local_symbol_table.set_table_scope(local);
}
Data_Type Procedure::get_return_type()
{
return return_type;
}
bool Procedure::variable_in_symbol_list_check(string variable)
{
return local_symbol_table.variable_in_symbol_list_check(variable);
}
bool Procedure::variable_in_argument_list_check(string variable)
{
return argument_symbol_table.variable_in_symbol_list_check(variable);
}
Symbol_Table_Entry & Procedure::get_symbol_table_entry(string variable_name)
{
return local_symbol_table.get_symbol_table_entry(variable_name);
}
Symbol_Table_Entry & Procedure::get_argument_table_entry(string variable_name)
{
return argument_symbol_table.get_symbol_table_entry(variable_name);
}
Argument_Table & Procedure::get_argument_symbol_table(){
return argument_symbol_table;
}
bool Procedure::is_body_defined(){
if(basic_block_list.size() > 0)
return true;
else
return false;
}
bool Procedure ::check_parameter_local_var(){
list<Symbol_Table_Entry *>::iterator i;
for (i = argument_symbol_table.variable_table.begin(); i != argument_symbol_table.variable_table.end(); i++)
{
if(local_symbol_table.variable_in_symbol_list_check((*i)->get_variable_name())){
return true;
}
}
return false;
}
void Procedure::print(ostream & file_buffer)
{
file_buffer << PROC_SPACE << "Procedure: " << name << ", Return Type: ";
if(return_type == void_data_type)
file_buffer << "VOID";
else if(return_type == float_data_type)
file_buffer << "FLOAT";
else
file_buffer << "INT";
file_buffer << "\n";
if ((command_options.is_show_symtab_selected()) || (command_options.is_show_program_selected()))
{
file_buffer << " Fromal Parameter List\n";
argument_symbol_table.print(file_buffer);
file_buffer << " Local Declarartions\n";
local_symbol_table.print(file_buffer);
}
if ((command_options.is_show_program_selected()) || (command_options.is_show_ast_selected()))
{
list<Basic_Block *>::iterator i;
for(i = basic_block_list.begin(); i != basic_block_list.end(); i++)
(*i)->print_bb(file_buffer);
}
}
Basic_Block & Procedure::get_start_basic_block()
{
list<Basic_Block *>::iterator i;
i = basic_block_list.begin();
return **i;
}
Basic_Block * Procedure::get_next_bb(Basic_Block & current_bb)
{
bool flag = false;
list<Basic_Block *>::iterator i;
if(current_bb.get_successor() == -1){
for(i = basic_block_list.begin(); i != basic_block_list.end(); i++)
{
if((*i)->get_bb_number() == current_bb.get_bb_number())
{
flag = true;
continue;
}
if (flag)
return (*i);
}
}
else{
for(i = basic_block_list.begin(); i != basic_block_list.end(); i++)
{
if((*i)->get_bb_number() == current_bb.get_successor())
{
return (*i);
}
}
}
if(current_bb.get_successor() == -2){
return NULL;
}
return NULL;
}
Eval_Result & Procedure::evaluate(Local_Environment & eval_env , ostream & file_buffer)
{
local_symbol_table.create(eval_env);
Eval_Result * result = NULL;
file_buffer << PROC_SPACE << "Evaluating Procedure << " << name << " >>\n";
file_buffer << LOC_VAR_SPACE << "Local Variables (before evaluating):\n";
eval_env.print(file_buffer);
file_buffer << "\n";
Basic_Block * current_bb = &(get_start_basic_block());
while (current_bb)
{
result = &(current_bb->evaluate(eval_env, file_buffer));
current_bb = get_next_bb(*current_bb);
}
file_buffer << "\n\n";
file_buffer << LOC_VAR_SPACE << "Local Variables (after evaluating) Function: << " << name << " >>\n";
string var_return = "return";
if(result->get_result_enum() != void_result ){
if(result->get_result_enum() == int_result){
Eval_Result_Value_Int * j = new Eval_Result_Value_Int();
j->set_value_int(result->get_int_value());
eval_env.put_variable_value(*j,var_return);
}
else if(result->get_result_enum() == float_result){
Eval_Result_Value_Float * j = new Eval_Result_Value_Float();
j->set_value_float(result->get_float_value());
eval_env.put_variable_value(*j,var_return);
}
}
//else if(return_type != void_return_type)
eval_env.print(file_buffer);
/*if(result->get_result_enum() != void_result ){
if(result->get_result_enum() == int_result)
file_buffer << VAR_SPACE << "return : " << (int) result->get_value()<<"\n";
else if(result->get_result_enum() == float_result)
file_buffer << VAR_SPACE << "return : " << result->get_value()<<"\n";
}*/
return *result;
}
/*
Eval_Result & Procedure::evaluate(ostream & file_buffer)
{
Local_Environment & eval_env = *new Local_Environment();
local_symbol_table.create(eval_env);
Eval_Result * result = NULL;
file_buffer << PROC_SPACE << "Evaluating Procedure " << name << "\n";
file_buffer << LOC_VAR_SPACE << "Local Variables (before evaluating):\n";
eval_env.print(file_buffer);
file_buffer << "\n";
Basic_Block * current_bb = &(get_start_basic_block());
while (current_bb)
{
result = &(current_bb->evaluate(eval_env, file_buffer));
current_bb = get_next_bb(*current_bb);
}
file_buffer << "\n\n";
file_buffer << LOC_VAR_SPACE << "Local Variables (after evaluating):\n";
eval_env.print(file_buffer);
return *result;
}
*/
void Procedure::compile()
{
// assign offsets to local symbol table
argument_symbol_table.set_start_offset_of_first_symbol(8);
argument_symbol_table.set_size(4);
argument_symbol_table.assign_offsets();
// assign offsets to local symbol table
local_symbol_table.set_start_offset_of_first_symbol(4);
local_symbol_table.set_size(4);
local_symbol_table.assign_offsets();
// compile the program by visiting each basic block
list<Basic_Block *>::iterator i;
for(i = basic_block_list.begin(); i != basic_block_list.end(); i++){
(*i)->compile();
}
}
void Procedure::print_icode(ostream & file_buffer)
{
file_buffer << " Procedure: " << name << "\n";
file_buffer << " Intermediate Code Statements\n";
list<Basic_Block *>::iterator i;
for (i = basic_block_list.begin(); i != basic_block_list.end(); i++)
(*i)->print_icode(file_buffer);
}
void Procedure::print_assembly(ostream & file_buffer)
{
print_prologue(file_buffer);
list<Basic_Block *>::iterator i;
for(i = basic_block_list.begin(); i != basic_block_list.end(); i++)
(*i)->print_assembly(file_buffer);
print_epilogue(file_buffer);
}
void Procedure::print_prologue(ostream & file_buffer)
{
stringstream prologue;
prologue << "\n\
.text \t\t\t# The .text assembler directive indicates\n\
.globl " << name << "\t\t# The following is the code (as oppose to data)\n";
prologue << name << ":\t\t\t\t# .globl makes main know to the \n\t\t\t\t# outside of the program.\n\
# Prologue begins \n\
sw $ra, 0($sp)\t\t# Save the return address\n\
sw $fp, -4($sp)\t\t# Save the frame pointer\n\
sub $fp, $sp, 8\t\t# Update the frame pointer\n";
int size = local_symbol_table.get_size();
size = -size;
if (size > 0)
prologue << "\n\tsub $sp, $sp, " << (size + 8) << "\t\t# Make space for the locals\n";
else
prologue << "\n\tsub $sp, $sp, 8\t\t# Make space for the locals\n";
prologue << "# Prologue ends\n\n";
file_buffer << prologue.str();
}
void Procedure::print_epilogue(ostream & file_buffer)
{
stringstream epilogue;
int size = local_symbol_table.get_size();
size = -size;
epilogue << "\n# Epilogue Begins\n";
epilogue << "epilogue_" << name << ":\n";
if (size > 0)
epilogue << "\tadd $sp, $sp, " << (size + 8) << "\n";
else
epilogue << "\tadd $sp, $sp, 8\n";
epilogue << "\tlw $fp, -4($sp) \n\tlw $ra, 0($sp) \n\tjr $31\t\t# Jump back to the called procedure\n# Epilogue Ends\n\n";
file_buffer << epilogue.str();
}
|
#include <DynamixelSerial.h>
#include <Arduino.h>
#include <SoftwareSerial.h>
#include <PacketSerial.h>
#define actuatorSSerial_RX 10
#define actuatorSSerial_TX 11
#define actuatorSSerial_Baud 9600
#define Dynamixel_Baud 1000000
#define DIRECTION_PIN 8
PacketSerial ActuatorPacketSerial;
SoftwareSerial actuatorSS(actuatorSSerial_RX, actuatorSSerial_TX);
int x; uint8_t buf[3];
void actuatoronPacketReceived(const uint8_t* buffer, size_t size)
{
switch(buffer[1]) {
/*
* Dynamixel.move(ID, Position);
*/
case 'm':
int calc;
calc = (int)((1024 / 255) * buffer[3]);
Dynamixel.move(buffer[2], calc);
break;
/*
* Dynamixel.moveSpeed(ID, Position, Speed);
*/
case 's':
int calc_angle, calc_speed;
calc_angle = (int)((1024 / 255) * buffer[3]);
calc_speed = (int)((1024 / 255) * buffer[4]);
Dynamixel.moveSpeed(buffer[2], calc_angle, calc_speed);
break;
/*
* Dynamixel.moving(ID)
*/
case 'M':
x = Dynamixel.moving(buffer[2]);
buf[0] = buffer[0];
buf[1] = buffer[1];
buf[2] = x;
ActuatorPacketSerial.send(buf, sizeof(buf)/sizeof(buf)[0]);
break;
/*
* Dynamixel.readPosition(ID);
*/
case 'p':
x = Dynamixel.readPosition(buffer[2]);
buf[0] = buffer[1];
buf[1] = x >> 8;
buf[2] = x & 0xFF;
ActuatorPacketSerial.send(buf, sizeof(buf)/sizeof(buf)[0]);
break;
/*
* Dynamixel.readVoltage(ID)
*/
case 'v':
x = Dynamixel.readVoltage(buffer[2]);
buf[0] = buffer[1];
buf[1] = x >> 8;
buf[2] = x & 0xFF;
ActuatorPacketSerial.send(buf, sizeof(buf)/sizeof(buf)[0]);
break;
/*
* Dynamixel.readTemparature
*/
case 't':
x = Dynamixel.readTemperature(buffer[2]);
buf[0] = buffer[1];
buf[1] = x >> 8;
buf[2] = x & 0xFF;
ActuatorPacketSerial.send(buf, sizeof(buf)/sizeof(buf)[0]);
break;
}
}
void setup() {
Dynamixel.begin(Dynamixel_Baud, DIRECTION_PIN);
Dynamixel.move(10, Dynamixel.readPosition(10));
Dynamixel.move(4, Dynamixel.readPosition(4));
/* ACTUATOR PACKET SERIAL SETUP */
actuatorSS.begin(actuatorSSerial_Baud);
ActuatorPacketSerial.setStream(&actuatorSS);
ActuatorPacketSerial.setPacketHandler(&actuatoronPacketReceived);
}
void loop() {
ActuatorPacketSerial.update();
}
|
/*
* Buttons.h
*
* Created on: 29.01.2019
* Author: Igor
*/
#ifndef CLASSES_BUTTONS_H_
#define CLASSES_BUTTONS_H_
#include "cmsis_os.h"
#include "USBTask.h"
extern uint8_t start_parking_USB;
extern uint8_t start_obstacle_USB;
extern uint8_t start_parking_sent;
extern uint8_t start_obstacle_sent;
class Buttons {
private:
public:
void process();
uint8_t start1_state_of_pressing;
uint8_t start2_state_of_pressing;
uint8_t screen1_state_of_pressing;
uint8_t screen2_state_of_pressing;
uint8_t screen3_state_of_pressing;
uint8_t any_button_was_pressed;
void Init();
Buttons();
virtual ~Buttons();
};
extern Buttons buttons;
#endif /* CLASSES_BUTTONS_H_ */
|
#pragma once
#include "Predefines.h"
#include "EJobQueue.h"
class EGameInstance;
class EJobManager
{
public:
bool Init();
// 모든 스레드에서 이 함수를 호출합니다.
void ThreadProc();
// 스레드풀을 생성한다.
void InitThreadPool();
// 스레드 풀을 제거한다.
void DestroyThreadPool();
// 초기화가 완료되고 OnBeginPlay에서 각각 시스템은 Tick마다 실행되는 함수를 큐에 추가합니다.
// 틱마다 실행되어야 하는 component 시스템 함수는 스스로 자기 자신을 작업큐에 넣습니다.
//
// @param1 : 소유자 Entity의 ID
// @param2 : 연산대상 ComponentID ComponentSystemIndex와 ComponentIndex로 파싱된다.
// @param3 : 수행해야하는 연산 OperationIndex (enum)
// @param4 : 해당 연산을 수행을 원하는 경우 EActiveOperation::True(기본값, 생략가능)
// 비활성화를 원하는 경우 EActiveOperation::False
void PushJob(int ownerID, int ComponentID, int OperationIndex, int activeOperation = 0);
public:
//inline EJobQueue* GetJobQueue() const
//{
// return m_pJobQueue;
//}
private:
EGameInstance* m_GI;
// 조건변수 스레드 대기 처리에 사용한다.
// condition_variable m_ConVar;
// 잡큐의 현재 크기를 바탕으로 스레드풀의 활성 비활성을 제어한다.
// -1 : 종료, 0 : 스레드 대기(일시중지, 작업없음 상황)
// 1~그이상 : 세마포어 차감 후 작동시작
LONG m_Sema = 0;
// 스레드가 현재 게임 상황에 맞춘 특별한 처리를 하도록 만드는 경우에 사용함 현재는 해당사항 없음
atomic<uint16> m_GameStateFlag;
// Job 저장되는 큐
EJobQueue* m_pJobQueue;
// 현재 컴퓨터의 가용 논리코어의 절반
int m_NumCore;
// 생성한 스레드 배열
vector<std::thread> vThread;
// 스핀락으로 스레드풀 대기
DECLARE_SINGLE(EJobManager)
};
|
#ifndef __FACTORY_HPP__
#define __FACTORY_HPP__
#include "base.hpp"
#include "op.hpp"
#include "rand.hpp"
#include "add.hpp"
#include "sub.hpp"
#include "mult.hpp"
#include "div.hpp"
#include "pow.hpp"
#include <string>
#include <iostream>
#include <queue>
#include <stack>
#include <vector>
class factory{
public:
factory(){};
Base* parse(char** input, int length){
std::queue<char*> num;
std::queue<char*> op;
std::string temp;
for(int i = 1; i < length; ++i) {
temp = static_cast<std::string>(input[i]);
if (isdigit(temp[0]) || isdigit(temp[1])) {
num.push(input[i]);
} else if (temp == "+" || temp == "-" || temp == "*" || temp == "/" || temp == "**"){
op.push(input[i]);
} else {
std::cout << "Please type equation again." << std::endl;
return nullptr;
}
}
if ((num.size()-1) != op.size()){
std::cout << "Please type equation again." << std::endl;
return nullptr;
}
std::vector<Base*> calculate;
int sz = num.size();
for(int i = 0; i < sz; ++i){
Op* in = new Op(stod(static_cast<std::string>(num.front())));
calculate.push_back(in);
num.pop();
}
std::stack<Base*> eval;
for(int i = sz; i > 0; --i){
eval.push(calculate[i - 1]);
}
Base* left;
Base* right;
Base* tempRes;
double numRes;
while(!op.empty()){
std::string ope = static_cast<std::string>(op.front());
if (ope == "+"){
left = eval.top();
eval.pop();
right = eval.top();
eval.pop();
tempRes = new Add(left, right);
eval.push(tempRes);
op.pop();
} else if (ope == "-"){
left = eval.top();
eval.pop();
right = eval.top();
eval.pop();
tempRes = new Sub(left, right);
eval.push(tempRes);
op.pop();
} else if (ope == "*") {
left = eval.top();
eval.pop();
right = eval.top();
eval.pop();
tempRes = new Mult(left, right);
eval.push(tempRes);
op.pop();
} else if (ope == "/") {
left = eval.top();
eval.pop();
right = eval.top();
eval.pop();
tempRes = new Div(left, right);
eval.push(tempRes);
op.pop();
} else if (ope == "**") {
left = eval.top();
eval.pop();
right = eval.top();
eval.pop();
tempRes = new Pow(left, right);
eval.push(tempRes);
op.pop();
}
}
return eval.top();
}
};
#endif
|
#include<iostream>
#include <sstream>
#include <string>
#include "main.h"
#include "timer.h"
#include "ball.h"
#include "enemy.h"
#include "background.h"
#include "porcupine.h"
using namespace std;
GLMatrices Matrices;
GLuint programID;
GLFWwindow *window;
/**************************
* Customizable functions *
**************************/
Ball ball1;
Enemy en[50];
Background back;
Porcupine po;
int flag = 0, i ,score = 0, val = -1, level = 1;
float screen_zoom = 1, screen_center_x = 0, screen_center_y = 0;
Timer t60(1.0 / 60);
/* Render the scene with openGL */
/* Edit this function according to your assignment */
void draw() {
// clear the color and depth in the frame buffer
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// use the loaded shader program
// Don't change unless you know what you are doing
glUseProgram (programID);
// Eye - Location of camera. Don't change unless you are sure!!
// glm::vec3 eye ( 5*cos(camera_rotation_angle*M_PI/180.0f), 0, 5*sin(camera_rotation_angle*M_PI/180.0f) );
// Target - Where is the camera looking at. Don't change unless you are sure!!
// glm::vec3 target (0, 0, 0);
// Up - Up vector defines tilt of camera. Don't change unless you are sure!!
// glm::vec3 up (0, 1, 0);
// Compute Camera matrix (view)
// Matrices.view = glm::lookAt( eye, target, up ); // Rotating Camera for 3D
// Don't change unless you are sure!!
Matrices.view = glm::lookAt(glm::vec3(0, 0, 3), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); // Fixed camera for 2D (ortho) in XY plane
// Compute ViewProject matrix as view/camera might not be changed for this frame (basic scenario)
// Don't change unless you are sure!!
glm::mat4 VP = Matrices.projection * Matrices.view;
// Send our transformation to the currently bound shader, in the "MVP" uniform
// For each model you render, since the MVP will be different (at least the M part)
// Don't change unless you are sure!!
glm::mat4 MVP; // MVP = Projection * View * Model
// Scene render
back.draw(VP, level);
if(level > 1)
{
po.draw(VP);
}
ball1.draw(VP);
for(i = 0 ; i < 40 ; i++)
{
en[i].draw(VP);
}
}
void tick_input(GLFWwindow *window)
{
int left = glfwGetKey(window, GLFW_KEY_LEFT);
int right = glfwGetKey(window, GLFW_KEY_RIGHT);
int up = glfwGetKey(window, GLFW_KEY_UP);
if(!left && !right && !up && ball1.position.x > -2.9f && ball1.position.x < -2.2f && ball1.position.y < -2.0f)
{
ball1.position.x += 0.01f;
ball1.position.y = ball1.get_y();
ball1.rotation -= (15/3.14159);
}
if(!left && !right && !up && ball1.position.x > -2.2f && ball1.position.x < -1.5f && ball1.position.y < -2.0f)
{
ball1.position.x -= 0.01f;
ball1.position.y = ball1.get_y();
ball1.rotation += (15/3.14159);
}
if(left && ball1.position.x >= -3.75f)
{
ball1.position.x -= 0.05f;
ball1.rotation += (30/3.14159);
if(ball1.position.y <= -2.0f && ball1.yspeed == 0.2)
{
ball1.position.y = ball1.get_y();
}
}
if(right && ball1.position.x <= 3.75f)
{
ball1.position.x += 0.05f;
ball1.rotation -= (30/3.14159);
if(ball1.position.y <= -2.0f && ball1.yspeed == 0.2)
{
ball1.position.y = ball1.get_y();
}
}
if((up && flag==0) || (ball1.position.y > ball1.get_y() && flag==1))
{
ball1.position.y += ball1.yspeed;
if(up && !flag && ball1.position.x > -2.9f && ball1.position.x < -1.5f)
{
ball1.yspeed = 0.15f;
}
ball1.yspeed -= 0.01;
flag = 1;
}
else
{
if(ball1.position.y < ball1.get_y() && ball1.yspeed == 0.2)
{
ball1.position.y = ball1.get_y();
}
flag = 0;
ball1.yspeed = 0.2;
}
}
void tick_elements() {
ball1.tick();
po.tick();
if(po.position.x <= -1.0f || po.position.x >= 1.0f) {
po.speed = -po.speed;
}
for(i = 0 ; i < 40 ; i++)
{
en[i].tick();
}
for(i = 0; i < 40 ; i++)
{
if(!en[i].slope && ball1.yspeed < 0 && detect_slope(ball1.bounding_box(), en[i].bounding_slope()))
{
val = 4;
ball1.xspeed = 0.2f / tan(en[i].theta * 3.14159 / 180);
ball1.yspeed = 0.2f;
flag = 1;
}
else if(en[i].slope && detect_collision(ball1.bounding_box(), en[i].bounding_box()) && (ball1.yspeed < 0))
{
ball1.yspeed = 0.2;
flag = 1;
if(en[i].r < 0.13)
{
score += 15;
}
else if(en[i].r > 0.17)
{
score += 5;
}
else
{
score += 10;
}
en[i].position.x = rand() % 20 - 24.0f;
en[i].position.y = (rand() % 3 - 1) + (rand() % 100) / 100.0;
en[i].speed = (rand() % 20) / 1000.0 + 0.01;
}
}
if(ball1.position.x >= 1.65f && ball1.position.x <= 2.35f && ball1.yspeed < 0 && ball1.position.y <= -1.65f && ball1.position.y >= -1.8f )
{
ball1.yspeed = 0.3f;
flag = 1;
}
if(ball1.position.y > 2.7f && ball1.position.y < 3.3f && ball1.position.x > -2.6f && level > 2)
{
float a = ball1.position.x + 5.0f;
ball1.xspeed -= a / 300;
}
else if(val < 0)
{
ball1.xspeed = 0;
}
val--;
if(detect_collision_porcupine(ball1.bounding_box(), po.bounding_porcupine()) && level > 1)
{
score -= 20;
ball1.position.x = 2.5f;
ball1.position.y = ball1.get_y();
}
if(score < 50)
{
level = 1;
}
else if(score >= 50 && score < 100)
{
level = 2;
}
else if(score >= 100)
{
level = 3;
}
ostringstream str1, str2;
str1 << score;
str2 << level;
string str = str1.str();
string st = str2.str();
string temp = "SCORE : " + str + " LEVEL : " + st;
glfwSetWindowTitle(window, temp.c_str());
}
/* Initialize the OpenGL rendering properties */
/* Add all the models to be created here */
void initGL(GLFWwindow *window, int width, int height) {
/* Objects should be created before any other gl function and shaders */
// Create the models
double p, q, s;
int slope, t, col;
back = Background(0, 0);
ball1 = Ball(2.5, -2, 0, 0.2);
po = Porcupine(0, -2.2);
for(i = 0 ; i < 40 ; i++)
{
col = rand() % 4;
t = rand() % 8;
p = rand() % 20 - 24.0f;
q = (rand() % 3 - 1) + (rand() % 100) / 100.0;
s = (rand() % 20) / 1000.0 + 0.01;
en[i].r = (rand() %10) / 100.0 + 0.1001;
if(t == 0)
{
slope = 0;
}
else
{
slope = 1;
}
if(col == 0)
{
en[i] = Enemy(en[i].r, (float)p, (float)q, s, slope, COLOR_ENEMY);
}
else if(col == 1)
{
en[i] = Enemy(en[i].r, (float)p, (float)q, s, slope, COLOR_YELLOW);
}
else if(col == 2)
{
en[i] = Enemy(en[i].r, (float)p, (float)q, s, slope, COLOR_BLUE);
}
else
{
en[i] = Enemy(en[i].r, (float)p, (float)q, s, slope, COLOR_GREEN);
}
}
// Create and compile our GLSL program from the shaders
programID = LoadShaders("Sample_GL.vert", "Sample_GL.frag");
// Get a handle for our "MVP" uniform
Matrices.MatrixID = glGetUniformLocation(programID, "MVP");
reshapeWindow (window, width, height);
// Background color of the scene
glClearColor (COLOR_BACKGROUND.r / 256.0, COLOR_BACKGROUND.g / 256.0, COLOR_BACKGROUND.b / 256.0, 0.0f); // R, G, B, A
glClearDepth (1.0f);
glEnable (GL_DEPTH_TEST);
glDepthFunc (GL_LEQUAL);
cout << "VENDOR: " << glGetString(GL_VENDOR) << endl;
cout << "RENDERER: " << glGetString(GL_RENDERER) << endl;
cout << "VERSION: " << glGetString(GL_VERSION) << endl;
cout << "GLSL: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << endl;
}
int main(int argc, char **argv) {
srand(time(0));
int width = 1000;
int height = 1000;
window = initGLFW(width, height);
initGL (window, width, height);
/* Draw in loop */
while (!glfwWindowShouldClose(window)) {
// Process timers
if (t60.processTick()) {
// 60 fps
// OpenGL Draw commands
draw();
// Swap Frame Buffer in double buffering
glfwSwapBuffers(window);
tick_elements();
tick_input(window);
}
// Poll for Keyboard and mouse events
glfwPollEvents();
}
quit(window);
}
bool detect_collision(bounding_box_t a, bounding_box_t b)
{
return ((abs(a.x - b.x) < (a.r + b.r)) &&
(0 < (a.y - b.y) <= (a.r + b.r)) &&
((a.r + 0.1) < sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2)) <= (a.r + b.r)));
}
bool detect_slope(bounding_box_t a, bounding_slope_t b)
{
float m, x0, y0, y_cord, d1, d;
m = tan(((90 + b.theta) * 3.14159) / 180);
x0 = (b.r + 0.1f) * cos(b.theta * 3.14159 / 180) + b.x;
y0 = (b.r + 0.1f) * sin(b.theta * 3.14159 / 180) + b.y;
d1 = 0.4f / sqrt(1 + (m*m));
d = abs((m * (a.x - x0)) - a.y + y0) / sqrt(1 + (m*m));
return ((a.x >= x0 - d1 - 0.1) && (a.x <= x0 + d1 + 0.1) && (d >= 0.18f) && (d <= 0.22f));
}
bool detect_collision_porcupine(bounding_box_t a, bounding_porcupine_t b)
{
return (((a.x <= b.x && a.x >= b.x - 0.4f) ||
(a.x >= b.x && a.x <= b.x + 0.4f)) && a.y == -2.0f);
}
void reset_screen()
{
float top = screen_center_y + 4 / screen_zoom;
float bottom = screen_center_y - 4 / screen_zoom;
float left = screen_center_x - 4 / screen_zoom;
float right = screen_center_x + 4 / screen_zoom;
Matrices.projection = glm::ortho(left, right, bottom, top, 0.1f, 500.0f);
}
|
//
// Created by frenchcommando on 2019-09-11.
//
#include "EulerProject.h"
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2002 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef OP_RESIZE_CORNER_H
#define OP_RESIZE_CORNER_H
#include "modules/widgets/OpWidget.h"
#include "modules/widgets/OpScrollbar.h"
class OpResizeCorner : public OpWidget
{
public:
// Implements OpWidget.
void OnBeforePaint();
/**
* Set the ScrollbarColors associated with this widget.
*
* If the resize corner is not skinned, it will be rendered using
* these colors.
*
* @param colors The new scrollbar colors.
*/
void SetScrollbarColors(const ScrollbarColors* colors) { this->colors = *colors; }
/** @return The current ScrollbarColors. */
ScrollbarColors& GetScrollbarColors() { return colors; }
protected:
ScrollbarColors colors;
};
/** OpWindowResizeCorner is the lower right corner grip, for resizing the window. */
class OpWindowResizeCorner : public OpResizeCorner
{
protected:
OpWindowResizeCorner();
public:
static OP_STATUS Construct(OpWindowResizeCorner** obj);
/** Set the Window that should be resized when this resizecorner is used. */
void SetTargetWindow(Window* window) { this->window = window; }
/** Enable/disable the resizecorner. When active is FALSE, it will be blank and disabled. */
void SetActive(BOOL active) { this->active = active; }
BOOL IsActive() { return active; }
// == Hooks ======================
void OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect);
#ifndef MOUSELESS
void OnSetCursor(const OpPoint &point);
void OnMouseMove(const OpPoint &point);
void OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks);
void OnMouseUp(const OpPoint &point, MouseButton button, UINT8 nclicks);
#endif // !MOUSELESS
private:
Window* window;
OpPoint down_point;
BOOL resizing;
BOOL active;
};
/**
* A widget which allows the user to resize other widgets.
*
* This class may be used to expose a handle which allow the user
* to resize a target widget.
*
* The original use-case is resizing textareas.
*/
class OpWidgetResizeCorner : public OpResizeCorner
{
public:
/**
* Create a new OpWidgetResizeCorner
*
* @param widget The OpWidget to make resizable. May not be NULL, and
* must exist as long as this OpWidget exists.
*/
OpWidgetResizeCorner(OpWidget* widget);
/**
* Indicates whether the OpWidgetResizeCorner has nearby scrollbars visible.
*
* This may change how the resize corner is drawn.
*
* @param horizontal TRUE if the horizontal scrollbar is visible.
* @param vertical TRUE if the vertical scrollbar is visible, and
* visually "touching" the resize corner.
*/
void SetHasScrollbars(BOOL horizontal, BOOL vertical)
{
this->has_horizontal_scrollbar = horizontal;
this->has_vertical_scrollbar = vertical;
}
// Overrides OpWidget.
void GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows);
void OnPaint(OpWidgetPainter* widget_painter, const OpRect& paint_rect);
#ifndef MOUSELESS
void OnSetCursor(const OpPoint& point);
void OnMouseMove(const OpPoint& point);
void OnMouseDown(const OpPoint& point, MouseButton button, UINT8 nclicks);
void OnMouseUp(const OpPoint& point, MouseButton button, UINT8 nclicks);
#endif // !MOUSELESS
private:
/** @return TRUE if the resize corner is enabled. */
BOOL IsActive() const;
/** @return TRUE if the associated widget has visible scrollbars. */
BOOL HasScrollbars() const { return has_horizontal_scrollbar || has_vertical_scrollbar; }
/**
* Resize the Target to the specified dimensions.
*
* @param target The target to resize.
* @param w The new width (in pixels).
* @param h The height (in pixels).
*/
void Resize(int w, int h);
/// The target OpWidget to make resizable.
OpWidget* widget;
/// The mousedown point (in document coordinates) when resizing begun.
OpPoint down_point;
/// TRUE if we are resizing.
BOOL resizing;
/// The width of 'widget' when the resizing begun.
INT32 down_width;
/// The height of 'widget' when the resizing begun.
INT32 down_height;
/// The width of 'widget' before it was modified.
INT32 original_width;
/// The height of 'widget' before it was modified.
INT32 original_height;
/// True if the target widget has scrollbars visible.
BOOL has_horizontal_scrollbar;
BOOL has_vertical_scrollbar;
};
#endif // OP_RESIZE_CORNER_H
|
#ifndef ETW_CONFIG_PLATFORM_RESTRICTION_VALIDATOR_H_
#define ETW_CONFIG_PLATFORM_RESTRICTION_VALIDATOR_H_
#include "ValidatorInterface.h"
#include "PlatformValidatorInterface.h"
#include <string>
namespace etw {
class PlatformRestrictionValidator : public PlatformValidatorInterface
{
public:
PlatformRestrictionValidator(std::string platform, ValidatorInterface *v);
int validateOption(std::string platform, OptionInterface *op);
private:
std::string my_platform;
ValidatorInterface *my_validator;
};
PlatformValidatorInterface *PlatformRestriction(std::string platform, ValidatorInterface *v);
}
#endif
|
#pragma once
#include <string>
//fight : levelid = 0
//hundred :
//01(2) + gameid(8) + levelid(2) + startid(6) + (14)
#define ROBOT_FLAG_OFFSET (30)
#define GAME_ID_OFFSET (22)
#define LEVEL_ID_OFFSET (17)
#define START_ID_OFFSET (12)
#define MAX_ROBOT_NUMBER (2048)
#define IS_ROBOT_UID(uid) (((uid >> ROBOT_FLAG_OFFSET) && 0x01) == 1)
namespace RobotUtil
{
bool makeRobotInfo(const std::string& headlink, int &sex, std::string &headurl, int &uid);
int getRobotStartUid(int gameid, int levelid, int startid);
bool makeRobotNameSex(std::string headlink, std::string &name, int &sex, std::string &headurl);
}
|
//
// Created by gaoxiang on 19-5-2.
//
#include "myslam/backend.h"
#include "myslam/algorithm.h"
#include "myslam/feature.h"
#include "myslam/g2o_types.h"
#include "myslam/map.h"
#include "myslam/mappoint.h"
namespace myslam {
Backend::Backend() {
backend_running_.store(true);
backend_thread_ = std::thread(std::bind(&Backend::BackendLoop, this));
}
void Backend::UpdateMap() {
std::unique_lock<std::mutex> lock(data_mutex_);
map_update_.notify_one();
}
void Backend::Stop() {
backend_running_.store(false);
map_update_.notify_one();
backend_thread_.join();
}
void Backend::BackendLoop() {
while (backend_running_.load()) {
std::unique_lock<std::mutex> lock(data_mutex_);
map_update_.wait(lock);
/// 后端仅优化激活的Frames和Landmarks
Map::KeyframesType active_kfs = map_->GetActiveKeyFrames();
Map::LandmarksType active_landmarks = map_->GetActiveMapPoints();
Optimize(active_kfs, active_landmarks);
}
}
void Backend::Optimize(Map::KeyframesType &keyframes,
Map::LandmarksType &landmarks) {
// setup g2o
typedef g2o::BlockSolver_6_3 BlockSolverType;
typedef g2o::LinearSolverCSparse<BlockSolverType::PoseMatrixType>
LinearSolverType;
auto solver = new g2o::OptimizationAlgorithmLevenberg(
g2o::make_unique<BlockSolverType>(
g2o::make_unique<LinearSolverType>()));
g2o::SparseOptimizer optimizer;
optimizer.setAlgorithm(solver);
// pose 顶点,使用Keyframe id
std::map<unsigned long, VertexPose *> vertices;
unsigned long max_kf_id = 0;
for (auto &keyframe : keyframes) {
auto kf = keyframe.second;
VertexPose *vertex_pose = new VertexPose(); // camera vertex_pose
vertex_pose->setId(kf->keyframe_id_);
vertex_pose->setEstimate(kf->Pose());
optimizer.addVertex(vertex_pose);
if (kf->keyframe_id_ > max_kf_id) {
max_kf_id = kf->keyframe_id_;
}
vertices.insert({kf->keyframe_id_, vertex_pose});
}
// 路标顶点,使用路标id索引
std::map<unsigned long, VertexXYZ *> vertices_landmarks;
// K 和左右外参
Mat33 K = cam_left_->K();
SE3 left_ext = cam_left_->pose();
SE3 right_ext = cam_right_->pose();
// edges
int index = 1;
double chi2_th = 5.991; // robust kernel 阈值
std::map<EdgeProjection *, Feature::Ptr> edges_and_features;
for (auto &landmark : landmarks) {
if (landmark.second->is_outlier_) continue;
unsigned long landmark_id = landmark.second->id_;
auto observations = landmark.second->GetObs();
for (auto &obs : observations) {
if (obs.lock() == nullptr) continue;
auto feat = obs.lock();
if (feat->is_outlier_ || feat->frame_.lock() == nullptr) continue;
auto frame = feat->frame_.lock();
EdgeProjection *edge = nullptr;
if (feat->is_on_left_image_) {
edge = new EdgeProjection(K, left_ext);
} else {
edge = new EdgeProjection(K, right_ext);
}
// 如果landmark还没有被加入优化,则新加一个顶点
if (vertices_landmarks.find(landmark_id) ==
vertices_landmarks.end()) {
VertexXYZ *v = new VertexXYZ;
v->setEstimate(landmark.second->Pos());
v->setId(landmark_id + max_kf_id + 1);
v->setMarginalized(true);
vertices_landmarks.insert({landmark_id, v});
optimizer.addVertex(v);
}
edge->setId(index);
edge->setVertex(0, vertices.at(frame->keyframe_id_)); // pose
edge->setVertex(1, vertices_landmarks.at(landmark_id)); // landmark
edge->setMeasurement(toVec2(feat->position_.pt));
edge->setInformation(Mat22::Identity());
auto rk = new g2o::RobustKernelHuber();
rk->setDelta(chi2_th);
edge->setRobustKernel(rk);
edges_and_features.insert({edge, feat});
optimizer.addEdge(edge);
index++;
}
}
// do optimization and eliminate the outliers
optimizer.initializeOptimization();
optimizer.optimize(10);
int cnt_outlier = 0, cnt_inlier = 0;
int iteration = 0;
while (iteration < 5) {
cnt_outlier = 0;
cnt_inlier = 0;
// determine if we want to adjust the outlier threshold
for (auto &ef : edges_and_features) {
if (ef.first->chi2() > chi2_th) {
cnt_outlier++;
} else {
cnt_inlier++;
}
}
double inlier_ratio = cnt_inlier / double(cnt_inlier + cnt_outlier);
if (inlier_ratio > 0.5) {
break;
} else {
chi2_th *= 2;
iteration++;
}
}
for (auto &ef : edges_and_features) {
if (ef.first->chi2() > chi2_th) {
ef.second->is_outlier_ = true;
// remove the observation
ef.second->map_point_.lock()->RemoveObservation(ef.second);
} else {
ef.second->is_outlier_ = false;
}
}
LOG(INFO) << "Outlier/Inlier in optimization: " << cnt_outlier << "/"
<< cnt_inlier;
// Set pose and lanrmark position
for (auto &v : vertices) {
keyframes.at(v.first)->SetPose(v.second->estimate());
}
for (auto &v : vertices_landmarks) {
landmarks.at(v.first)->SetPos(v.second->estimate());
}
}
} // namespace myslam
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
//
// Musical notes are are given the following 12 names, in
// ascending order:
//
//
//
//
// A, A#, B, C, C#, D, D#, E, F, F#, G, G#
//
//
//
// The names repeat for higher and lower notes,
// so the note one step higher than "G#" is "A"
// and the note 5 steps lower than "B" is "F#".
// Notes that are a multiple of 12 steps apart have the same
// name, and for our purposes we will consider them equivalent.
//
//
//
// Guitars have a number of strings, and each string is tuned
// to sound one of the 12 notes.
// The note each string sounds is called its "open" note.
// Underneath the strings are frets, numbered starting at 1,
// which are used to change the note a string sounds.
// If you press a string against the i-th fret with your
// finger, the note will be i steps higher than the string's
// open note.
// (i.e., if you press a string tuned to "C#" against the 3rd
// fret, it will sound the note "E").
//
//
//
// Chords are sets of notes played at the same time.
// To play a chord on a guitar, each string must sound one of
// the notes in the chord,
// and each note in the chord must be played on at least one
// string.
//
//
//
// There can be many ways to play the same chord.
// We measure the difficulty of one way to play a chord as
// the amount you must stretch your fingers to reach the
// required frets.
// Calculate this as the lowest fret used subtracted from the
// highest fret used, plus 1.
// Only consider the strings which are pressed against frets
// -- the strings that are not pressed against frets (and,
// thus, sound their open note) do not affect the difficultly
// of a chord.
// If a chord can be played without using any frets at all,
// its difficulty is zero.
//
//
//
// You are given a String[] strings, each element of which is
// the open note of one string on the guitar,
// and a String[] chord, each element of which is one note in
// a chord.
// Return the lowest possible difficulty value necessary to
// play that chord.
//
//
//
// DEFINITION
// Class:GuitarChords
// Method:stretch
// Parameters:vector <string>, vector <string>
// Returns:int
// Method signature:int stretch(vector <string> strings,
// vector <string> chord)
//
//
// CONSTRAINTS
// -strings and chord will each contain between 1 and 6
// elements, inclusive.
// -chord will not contain more elements than strings.
// -Each element of strings and chord will be one of the 12
// note names given in the problem statement.
// -chord will not contain any duplicate elements.
//
//
// EXAMPLES
//
// 0)
// { "A", "C", "F" }
// { "C#", "F#", "A#" }
//
// Returns: 1
//
// The three notes in the chord are each one step higher than
// the notes played by the three strings. So, you can play
// this chord by putting your finger on the 1st fret on all
// three strings. The answer is therefore: (1-1)+1.
//
// 1)
// { "E", "A", "D", "G", "B", "E" }
// { "E", "G#", "B" }
//
// Returns: 2
//
// The best way to play this chord is with your fingers on
// the following frets:
//
//
// string 0, "E": no fret, plays note "E"
// string 1, "A": fret #2, plays note "B"
// string 2, "D": fret #2, plays note "E"
// string 3, "G": fret #1, plays note "G#"
// string 4, "B": no fret, plays note "B"
// string 5, "E": no fret, plays note "E"
//
//
// All strings are playing a note in the chord, and each note
// in the chord is played on at least one string. The
// largest-numbered fret is 2, and the smallest is 1.
// Therefore the answer is (2-1)+1.
//
// 2)
// { "D#" }
// { "D#" }
//
// Returns: 0
//
//
//
// 3)
// { "E", "F" }
// { "F#", "D#" }
//
// Returns: 3
//
// You can play this chord with the 11th fret of the "E"
// string (playing the note "D#") and the 13th fret of the
// "F" string (playing the note "F#"). (13-11)+1 = 3.
//
// 4)
// { "C", "C", "C" }
// { "C", "E", "G" }
//
// Returns: 4
//
//
//
// END CUT HERE
#line 149 "GuitarChords.cc"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
VI st, ch;
int diff(int low, int high) {
int a1 = (high - low + 12) % 12;
int a2 = (low - high + 12) % 12;
return a1 < a2 ? a1 : a2;
}
int go(int pos, int set, int &low, int &high) {
if (pos == st.size()) {
if (set == 0) return 0;
return 1<<30;
}
int lb,hb;
fi(ch.size()) {
int fr = (ch[i] - st[pos] + 12) % 12;
int l1;
int h1;
int r1 = go(pos + 1, set & ~(1<<i), l1, h1);
if (r1 == 1<<30) continue;
if (r1 == 0) {
lb = fr;
hb = fr;
} else {
if (fr != 0) {
l1 = min(l1, fr);
h1 = max(h1, fr);
}
if (diff(l1, h1) < diff(lb,hb)) {
lb = l1;
hb = h1;
}
}
}
if (hb == 1<<30) return hb;
low = lb;
high = hb;
if (be == 0 )
return be;
return be + 1;
}
class GuitarChords
{
public:
int stretch(vector <string> strings, vector <string> chord)
{
map<string, int> notes;
// A, A#, B, C, C#, D, D#, E, F, F#, G, G#
notes["A"] = 0;
notes["A#"] = 1;
notes["B"] = 2;
notes["C"] = 3;
notes["C#"] = 4;
notes["D"] = 5;
notes["D#"] = 6;
notes["E"] = 7;
notes["F"] = 8;
notes["F#"] = 9;
notes["G"] = 10;
notes["G#"] = 11;
st.resize(strings.size());
ch.resize(chord.size());
fi(strings.size()) st[i] = notes[strings[i]];
fi(chord.size()) ch[i] = notes[chord[i]];
int low = 0;
int high = 0;
return go(0, (1 << ch.size()) - 1, low, high);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = { "A", "C", "F" }; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { "C#", "F#", "A#" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 1; verify_case(0, Arg2, stretch(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = { "E", "A", "D", "G", "B", "E" }; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { "E", "G#", "B" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; verify_case(1, Arg2, stretch(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = { "D#" }; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { "D#" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; verify_case(2, Arg2, stretch(Arg0, Arg1)); }
void test_case_3() { string Arr0[] = { "E", "F" }; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { "F#", "D#" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; verify_case(3, Arg2, stretch(Arg0, Arg1)); }
void test_case_4() { string Arr0[] = { "C", "C", "C" }; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { "C", "E", "G" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 4; verify_case(4, Arg2, stretch(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
GuitarChords ___test;
___test.run_test(-1);
}
// END CUT HERE
|
// Copyright (c) 2012-2017 The Cryptonote developers
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "gtest/gtest.h"
#include <cstdint>
#include <vector>
#include "CryptoNoteCore/CryptoNoteFormatUtils.h"
#define VEC_FROM_ARR(vec) \
std::vector<uint64_t> vec; \
for (size_t i = 0; i < sizeof(vec##_arr) / sizeof(vec##_arr[0]); ++i) \
{ \
vec.push_back(vec##_arr[i]); \
}
namespace
{
struct chunk_handler_t
{
void operator()(uint64_t chunk) const
{
m_chunks.push_back(chunk);
}
mutable std::vector<uint64_t> m_chunks;
};
struct dust_handler_t
{
dust_handler_t()
: m_dust(0)
, m_has_dust(false)
{
}
void operator()(uint64_t dust) const
{
m_dust = dust;
m_has_dust = true;
}
mutable uint64_t m_dust;
mutable bool m_has_dust;
};
class decompose_amount_into_digits_test : public ::testing::Test
{
protected:
chunk_handler_t m_chunk_handler;
dust_handler_t m_dust_handler;
};
}
TEST_F(decompose_amount_into_digits_test, is_correct_0)
{
std::vector<uint64_t> expected_chunks;
cn::decompose_amount_into_digits(0, 0, m_chunk_handler, m_dust_handler);
ASSERT_EQ(m_chunk_handler.m_chunks, expected_chunks);
ASSERT_EQ(m_dust_handler.m_has_dust, false);
}
TEST_F(decompose_amount_into_digits_test, is_correct_1)
{
std::vector<uint64_t> expected_chunks;
cn::decompose_amount_into_digits(0, 10, m_chunk_handler, m_dust_handler);
ASSERT_EQ(m_chunk_handler.m_chunks, expected_chunks);
ASSERT_EQ(m_dust_handler.m_has_dust, false);
}
TEST_F(decompose_amount_into_digits_test, is_correct_2)
{
uint64_t expected_chunks_arr[] = {10};
VEC_FROM_ARR(expected_chunks);
cn::decompose_amount_into_digits(10, 0, m_chunk_handler, m_dust_handler);
ASSERT_EQ(m_chunk_handler.m_chunks, expected_chunks);
ASSERT_EQ(m_dust_handler.m_has_dust, false);
}
TEST_F(decompose_amount_into_digits_test, is_correct_3)
{
std::vector<uint64_t> expected_chunks;
uint64_t expected_dust = 10;
cn::decompose_amount_into_digits(10, 10, m_chunk_handler, m_dust_handler);
ASSERT_EQ(m_chunk_handler.m_chunks, expected_chunks);
ASSERT_EQ(m_dust_handler.m_dust, expected_dust);
}
TEST_F(decompose_amount_into_digits_test, is_correct_4)
{
uint64_t expected_dust = 8100;
std::vector<uint64_t> expected_chunks;
cn::decompose_amount_into_digits(8100, 1000000, m_chunk_handler, m_dust_handler);
ASSERT_EQ(m_chunk_handler.m_chunks, expected_chunks);
ASSERT_EQ(m_dust_handler.m_dust, expected_dust);
}
TEST_F(decompose_amount_into_digits_test, is_correct_5)
{
uint64_t expected_chunks_arr[] = {100, 900000, 8000000};
VEC_FROM_ARR(expected_chunks);
cn::decompose_amount_into_digits(8900100, 10, m_chunk_handler, m_dust_handler);
ASSERT_EQ(m_chunk_handler.m_chunks, expected_chunks);
ASSERT_EQ(m_dust_handler.m_has_dust, false);
}
TEST_F(decompose_amount_into_digits_test, is_correct_6)
{
uint64_t expected_chunks_arr[] = {900000, 8000000};
VEC_FROM_ARR(expected_chunks);
uint64_t expected_dust = 100;
cn::decompose_amount_into_digits(8900100, 1000, m_chunk_handler, m_dust_handler);
ASSERT_EQ(m_chunk_handler.m_chunks, expected_chunks);
ASSERT_EQ(m_dust_handler.m_dust, expected_dust);
}
|
#include "Persona.h"
#include <sstream>
#include <iostream>
using std::stringstream;
using std::endl;
using std::cin;
using std::cout;
Persona::Persona(){
}
Persona::Persona(string n, string na, int e, string s, Elemento* el){
nombre=n;
nacion=na;
edad=e;
sexo=s;
elemento=el;
}
string Persona::getNombre(){
return nombre;
}
string Persona::getNacion(){
return nacion;
}
int Persona::getEdad(){
return edad;
}
string Persona::getSexo(){
return sexo;
}
Elemento* Persona::getElemento(){
return elemento;
}
string Persona::toString(){
stringstream retorno;
string r;
cout<<"Nombre: "<<nombre<<endl;
cout<<"Nacion: "<<nacion<<endl;
cout<<"Edad: "<<edad<<endl;
cout<<"Sexo: "<<sexo<<endl;
cout<<"Elemento: "<<elemento->toString();
r=retorno.str();
return r;
}
Persona::~Persona(){
delete elemento;
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
//
// Copyright (C) Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
#ifndef CHARSETDETECTOR_H_
#define CHARSETDETECTOR_H_
class CharsetDetector
{
public:
inline static bool StartsWithUTF16BOM(const void *buffer)
{
return 0xFEFF == *reinterpret_cast<const UINT16 *>(buffer) ||
0xFFFE == *reinterpret_cast<const UINT16 *>(buffer);
};
};
#endif /* CHARSETDETECTOR_H_ */
|
//
// am_pm_clock.cpp
// Summer_Assignment_1
//
// Created by карим on 6/5/19.
// Copyright © 2019 карим. All rights reserved.
//
#include "am_pm_clock.h"
#include <iostream>
am_pm_clock::am_pm_clock() :
hours(12),
minutes(0),
seconds(0),
am(true)
{}
am_pm_clock::am_pm_clock(unsigned int hrs, unsigned int mins,
unsigned int secs, bool am_val):
hours(hrs),
minutes(mins),
seconds(secs),
am(am_val)
{}
am_pm_clock::am_pm_clock(const am_pm_clock &clock):
hours(clock.hours),
minutes(clock.minutes),
seconds(clock.seconds),
am(clock.am)
{}
am_pm_clock& am_pm_clock::operator=(const am_pm_clock& clock){
this->hours = clock.hours;
this->minutes = clock.minutes;
this->seconds = clock.seconds;
this->am = clock.am;
return *this;
}
void am_pm_clock::toggle_am_pm(){
if(am == true) am = false;
else am = true;
}
void am_pm_clock::reset(){
hours = 12;
minutes = 0;
seconds = 0;
am = true;
}
void am_pm_clock::advance_one_sec(){ //It could be done with loop, but I decided that in that way the code wil be faster
seconds++;
if(seconds == 60){
seconds = 0;
minutes++;
}
if(minutes == 60){
minutes = 0;
hours++;
}
if(hours == 12) toggle_am_pm();
if(hours == 13) hours = 1;
}
void am_pm_clock::advance_n_secs(unsigned int n){ //I could use the function above, but I wanted not to use loops
seconds+=n;
if(seconds >= 60){
minutes+=seconds/60;
seconds = seconds%60;
}
if(minutes >= 60){
hours+=minutes/60;
minutes = minutes%60;
}
if(hours >= 12){
if((hours/12) % 2 == 1) toggle_am_pm();
hours = hours % 12;
if(hours == 0) hours = 12;
}
}
unsigned int am_pm_clock::get_hours() const{
return hours;
}
void am_pm_clock::set_hours(unsigned int hrs){
if(hrs > 0 && hrs < 13)
hours = hrs;
else throw std::invalid_argument("Hours only can be greater than 0 and less than 13!!!/n");
}
unsigned int am_pm_clock::get_minutes() const{
return minutes;
}
void am_pm_clock::set_minutes(unsigned int mins){
if(mins > 0 && mins < 60)
minutes = mins;
else throw std::invalid_argument("Minutes only can be greater than 0 and less than 60!!!/n");
}
unsigned int am_pm_clock::get_seconds() const{
return seconds;
}
void am_pm_clock::set_seconds(unsigned int secs){
if(secs > 0 && secs < 60)
seconds = secs;
else throw std::invalid_argument("Seconds only can be greater than 0 and less than 60!!!/n");
}
bool am_pm_clock::is_am() const{
return am;
}
void am_pm_clock::set_am(bool am_val){
if(am_val != true || am_val != false) throw std::invalid_argument("Boolean only can be false or true!!!/n");
am = am_val;
}
am_pm_clock::~am_pm_clock(){
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef ADDACTIONBUTTONCONTROLLER_H
#define ADDACTIONBUTTONCONTROLLER_H
#include "adjunct/quick/controller/SimpleDialogController.h"
class AddActionButtonController : public SimpleDialogController
{
public:
AddActionButtonController(OpToolbar * toolbar, BOOL is_button, OpInputAction * input_action, int pos, BOOL force);
OP_STATUS SetData(const uni_char* action_url, const uni_char* action_title);
private:
void InitL();
virtual void OnOk();
OpString m_actionurl;
OpString m_actiontitle;
INT32 m_pos;
BOOL m_force;
OpToolbar * m_toolbar;
OpInputAction * m_input_action;
BOOL m_is_button;
};
#endif // ADDACTIONBUTTONCONTROLLER_H
|
#include <bits/stdc++.h>
#define isnum(x) ('0' <= x && x <= '9')
#define read(x) do { \
x = 0, R::c = getchar(), R::m = 1; \
while (!isnum(R::c) && R::c != '-') R::c = getchar(); \
if (R::c == '-') R::c = getchar(), R::m = -1; \
while (isnum(R::c)) x = x * 10 + R::c - '0', R::c = getchar(); \
x *= R::m; \
} while (false)
namespace R { char c; int m; }
using namespace std;
#define sqr(x) ( (x) * (x) )
const int maxn = 1000010;
int n, m, p, s, e, x, y, z, l, r, u, v, cst;
int a[maxn], b[maxn], dis[maxn], q[maxn];
bool inq[maxn];
struct Edge {
int e, v;
};
vector < Edge > G[maxn];
int main() {
read(n); read(m);
for (int i = 1; i <= m; i++) {
read(x); read(y); read(z);
G[x].push_back( {y, z} );
G[y].push_back( {x, z} );
}
read(p);
for (int i = 1; i <= p; i++) {
read(s); read(e);
memset(dis, -1, sizeof(dis));
l = r = 1, q[1] = s, inq[s] = 1, dis[s] = 100001;
while (l <= r) {
u = q[l++];
inq[u] = 0;
for (int i = 0; i < G[u].size(); i++) {
v = G[u][i].e;
cst = G[u][i].v;
if (min(dis[u], cst) > dis[v]) {
dis[v] = min(dis[u], cst);
if (!inq[v]) {
inq[v] = 1;
q[++r] = v;
}
}
}
}
printf("%d\n", dis[e]);
}
return 0;
}
|
#include "CyclistTrackedObject.hpp"
CyclistTrackedObject::CyclistTrackedObject() {
this->ltr = 0;
this->framesAlive = 0;
}
CyclistTrackedObject::CyclistTrackedObject(cv::Point pt, cv::Rect rectangle, unsigned int id,
bool left2right) {
this->pt = pt;
this->pt0 = pt;
this->rect = rectangle;
this->id = id;
this->ltr = left2right;
this->framesAlive = 0;
}
void CyclistTrackedObject::Plot(cv::Mat &frame) {
cv::rectangle(frame, this->rect, cv::Scalar(0, 0, 255), 1);
}
int CyclistTrackedObject::GetId() {
return this->id;
}
|
#pragma once
#include <armadillo>
namespace Algorithms
{
class LinearImpute
{
public:
static void LinearImpute_Recovery(arma::mat &input);
// other function signatyures go here
};
} // namespace Algorithms
|
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TextTestRunner.h>
int main(int argc, char **argv) {
CppUnit::TextTestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
if(runner.run()) {
return EXIT_SUCCESS;
} else {
return EXIT_FAILURE;
}
}
|
#define _WINSOCKAPI_
#include "App_SSS.h"
#include "app_PBR.h"
//#include "app_edushi_VR.h"
#include "app_edushi.h"
//#include "app_VR.h"
#include "GLFWFramework.h"
//#include "edushiKey.h"
//#include "connection.h"
//#pragma comment(lib,"LibConnection.lib")
//#include "socketSceneLoader/SceneLoader.h"
std::function< void (int,int)> f;
void main() {
GLFWFrameWork fw;
auto app4 = new App_edushi;
//auto app4 = new App_edushi_VR;
//auto app4 = new App_VR;
fw.app = app4;
fw.Init();
//edushi_key ek;
//ek.app = app4;
//f = std::bind(&edushi_key::SwitchLogCam, ek, std::placeholders::_1, std::placeholders::_2);
//InteractionControler::KeyCallBacks.push_back(f);
fw.Loop();
return;
}
|
#include<fstream>
#include<iostream>
#include<string>
#include<list>
#include<cstdlib>
#include"dataEntry.h"
//loads previously recorded entries from file
//input: address to list which contains pointers to loaded entries, file object
//output 1 for success, 0 for fail
bool loadEntries(std::list<dataEntry*> &entriesPrev) {
std::ifstream file;
file.open("saveData.txt");
if (file.is_open()) {
std::string line; //line containing a single previous entry
double values[6] = { 0 }; // data, odo, litres, priceTotal, pricePerLitre, efficiency
std::string entry; //single entry value read from line
//iterate through each line in file for each data entry
while (std::getline(file, line)) {
//checks to see if on end of file
if (line.length() < 2) {
break;
}
int posStart = 0; //beginning of single value in line
int len = 0; //length of single value in line
int posVal = 0;
for (int i = 0; i <= line.length(); i++) {
if (line[i] == ' ' || i == line.length()) { //end of value
entry = line.substr(posStart, len);
values[posVal] = stod(entry, 0);
entry.clear();
posVal++;
posStart += len + 1;
len = 0;
continue;
}
else {
len++;;
}
}
//store values in new dataEntry object and pushes to passed in list
dataEntry* newEntry = new dataEntry((int)values[0], (int)values[1], values[2], values[3], values[4], values[5]);
entriesPrev.push_back(newEntry);
}
file.close();
return true;
}
return false;
}
//saves entries from list to file
//input: address to list which contains pointers to loaded entries, file object
//output 1 for success, 0 for fail
bool saveEntries(std::list<dataEntry*> &entries) {
std::ofstream file;
file.open("saveData.txt", std::fstream::out);
if (file.is_open()) {
for (std::list<dataEntry*>::iterator entry = entries.begin(); entry != entries.end(); ++entry) { //iterate through list and save each entry to file in order
(*entry)->saveEntry(file);
}
file.close();
return true;
}
return false;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-1999 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"
#include "modules/dom/src/domcore/comment.h"
DOM_Comment::DOM_Comment()
: DOM_CharacterData(COMMENT_NODE)
{
}
/* static */ OP_STATUS
DOM_Comment::Make(DOM_Comment *&comment, DOM_Node *reference, const uni_char *contents)
{
DOM_CharacterData *characterdata;
RETURN_IF_ERROR(DOM_CharacterData::Make(characterdata, reference, contents, TRUE, FALSE));
OP_ASSERT(characterdata->IsA(DOM_TYPE_COMMENT));
comment = (DOM_Comment *) characterdata;
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_Comment::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
if (property_name == OP_ATOM_nodeName)
{
DOMSetString(value, UNI_L("#comment"));
return GET_SUCCESS;
}
else
return DOM_CharacterData::GetName(property_name, value, origining_runtime);
}
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_set>
#include <cmath>
using namespace std;
void dfs(int v, vector<unordered_set<int>> &g, vector<int> &used, vector<int> &ans) {
used[v] = true;
for (auto to : g[v]) {
if (!used[to]) {
dfs(to, g, used, ans);
}
}
ans.push_back(v);
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, a, b;
cin >> n >> m;
vector<unordered_set<int>> g(n);
vector<int> used(n);
vector<int> ans;
for (int i = 0; i < m; i++) {
cin >> a >> b;
g[a - 1].insert(b - 1);
}
for (int i = 0; i < n; i++) {
if (!used[i])
dfs(i, g, used, ans);
}
reverse(ans.begin(), ans.end());
for (int i = 0; i < n - 1; i++) {
if (g[ans[i]].count(ans[i + 1]) == 0) {
cout << "NO";
exit(0);
}
}
cout << "YES";
return 0;
}
|
//I affirm that all code given below was written solely by me,
// Samantha Nix, and that any help I received adhered to the rules stated for this exam.
#include "Runner.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
void sortPace(vector<Runner>&);//Function to place the runners into files based on pace
int main()
{
vector<Runner> runners;//Creates a vector for the runners
string firstname, lastname;
int pace;
fstream registrants("registrants.txt", ios::in);
if (registrants.fail())
{
cout << "The file failed! :(" << endl;
}
while (registrants >> firstname >> lastname >> pace)
{
registrants >> firstname >> lastname >> pace;//Read in those values to the variables
runners.push_back(Runner(firstname, lastname, pace));//Push back object that is created by constructor with the values the variables were just assigned to
}
sort(runners.begin(), runners.end()); //Sort the values in the array
sortPace(runners); //Calls function to write the runners in the vector to text files
}
// function that sets the runner objects to the proper text file based on the pace
void sortPace(vector<Runner>& runners)
{
fstream white("white.txt", ios::out); // create fstream objects for each color
fstream yellow("yellow.txt", ios::out);
fstream green("green.txt", ios::out);
fstream orange("orange.txt", ios::out);
fstream blue("blue.txt", ios::out);
fstream lilac("lilac.txt", ios::out);
fstream red("red.txt", ios::out);
string first, last;
int pace;
for (int i = 0; i < runners.size(); i++)
{
first = runners[i].get_firstname(); // sets variable equal to the corresponding values for the specified object
last = runners[i].get_lastname();
pace = runners[i].get_pace();
if (pace >= 0 && pace <= 360)
{// pace parameters for white
white << first << " " << last << " " << pace << endl;//Write values into the white text file
}
if (pace >= 361 && pace <= 420)
{// pace parameters for yellow
yellow << first << " " << last << " " << pace << endl;//Write values into the yellow text file
}
if (pace >= 421 && pace <= 480)
{// pace parameters for green
green << first << " " << last << " " << pace << endl;//Write values into the green text file
}
if (pace >= 481 && pace <= 540)
{// pace parameters for orange
orange << first << " " << last << " " << pace << endl;//Write values into the orange text file
}
if (pace >= 541 && pace <= 600)
{// pace parameters for blue
blue << first << " " << last << " " << pace << endl;//Write values into the blue text file
}
if (pace >= 601 && pace <= 720)
{// pace parameters for lilac
lilac << first << " " << last << " " << pace << endl;//Write values into the lilac text file
}
if (pace >= 721 && pace <= 1200)
{// pace parameters for red
red << first << " " << last << " " << pace << endl; //Write values into red text file
}
}
white.close(); // closes fstream objects
yellow.close();
green.close();
orange.close();
blue.close();
lilac.close();
red.close();
}
|
#include"TuringMachine.h"
#include"StlSet.h"
#include"StlTransitionFunction.h"
#include"DLLTape.h"
#include"MachineStrategy.h"
TuringMachine* TuringMachine::instance = 0;
TuringMachine::TuringMachine()
{
this->startState = "";
this->alphabet = new StlSet<SymbolType>();
this->states = new StlSet<StatesType>();
this->finalStates = new StlSet<StatesType>();
this->transitionFunction = new StlTransitionFunction<TransitionKeyType, TransitionValueType>();
this->tape = new DLLTape<SymbolType>();
}
TuringMachine& TuringMachine::getInstance()
{
if(TuringMachine::instance == NULL)
{
TuringMachine::instance = new TuringMachine();
}
return *TuringMachine::instance;
}
AlphabetSet& TuringMachine::getAlphabet() const
{
return *(this->alphabet);
}
StatesSet& TuringMachine::getStatesSet() const
{
return *(this->states);
}
FinalStatesSet& TuringMachine::getFinalStates() const
{
return *(this->finalStates);
}
TransitionF& TuringMachine::getTransitionFunction() const
{
return *(this->transitionFunction);
}
MachineTape& TuringMachine::getTape() const
{
return *(this->tape);
}
void TuringMachine::setStartState(StatesType s)
{
this->startState = s;
}
StatesType TuringMachine::getCurrentState() const
{
return this->currentState;
}
void TuringMachine::setCurrentState(StatesType state)
{
this->currentState = state;
}
|
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <fstream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
class Printer {
static int id;
public:
int get_id() const { return id; }
void set_id(int value) { id = value; }
};
int main() {
Printer p;
auto id = p.get_id();
Printer p2;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
ofstream fout ("hps.out");
ifstream fin ("hps.in");
#define For(x) for(int i = 0; i < x; i++)
#define For2(x) for(int j = 0; j < x; j++)
#define Forv(vector) for(auto& k : vector)
int main(){
int n;
fin >> n;
vector<pair<int,int> > turns;
For(n){
int a,b;
fin >> a >> b;
if(a!=b){
pair<int,int> p(a,b);
turns.push_back(p);
}
}
int poss[6][3] = {{1,2,3}, {1,3,2},{2,1,3},{2,3,1},{3,1,2},{3,2,1}};
int maxm = 0;
For(6){
auto current = poss[i];
int win = 0;
Forv(turns){
if(current[k.first-1] == 1){
if(current[k.second-1] == 2){
win+=1;
}
}
else if(current[k.first-1] == 2){
if(current[k.second-1] == 3){
win+=1;
}
}
else{
if(current[k.second-1] == 1){
win+=1;
}
}
}
maxm=max(win,maxm);
}
fout<<maxm<<"\n";
}
|
/***************************************************************************
* Copyright (C) 2009 by Dario Freddi *
* drf54321@gmail.com *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#ifndef DATABASE_H
#define DATABASE_H
#include <QtCore/QList>
#include <QtCore/QMetaType>
#include "Package.h"
typedef struct __pmdb_t pmdb_t;
namespace Aqpm
{
class AQPM_EXPORT Database
{
public:
typedef QList<Database*> List;
virtual ~Database();
QString name() const;
QString path() const;
QStringList servers() const;
Package::List packages();
pmdb_t *alpmDatabase() const;
bool isValid() const;
private:
explicit Database(pmdb_t *db);
class Private;
Private *d;
friend class BackendThread;
};
}
Q_DECLARE_METATYPE(Aqpm::Database*)
Q_DECLARE_METATYPE(Aqpm::Database::List)
#endif // DATABASE_H
|
class Solution {
public:
int maxArea(vector<int>& height) {
int i = 0, j = height.size()-1, area = 0;
while(i < j){
int h = min(height[i], height[j]);
area = max(h*(j-i), area);
while(i < j && height[i] <= h) ++i;
while(i < j && height[j] <= h) --j;
}
return area;
}
};
|
#include "base_entity.h"
BaseEntity::BaseEntity(QObject * parent)
: Base(parent)
{
}
uuid BaseEntity::genUuid() {
char* id = new char[36];
QByteArray ba = QUuid::createUuid().toByteArray();
strcpy(id, (uuid) ba.mid(1, 36).data());
return (uuid) id;
}
int BaseEntity::timestamp() {
return QDateTime::currentDateTime().toTime_t();
}
uuid BaseEntity::getId() {
return this->_id;
}
void BaseEntity::setId(uuid id) {
this->_id = id;
}
void BaseEntity::setId(QByteArray id) {
char* _id = new char[36];
strcpy(_id, id.data());
this->_id = (uuid) _id;
}
|
SpreadsheetCell myCell(4);
cout<<myCell.getValue()<<endl;//correct
myCell.setString("9.0");
const SpreadsheetCell& anotherCell=myCell;//correct
cout<<anotherCell.getValue()<<endl;
anotherCell.setString("9.0");//incorrect
|
#include <iostream>
#include <cmath>
using namespace std;
class Gear
{
public:
bool teeth[8];
void rotate(bool direction);
};
void Gear::rotate(bool direction)
{
int offset = (direction) ? 7 : 1;
bool buff[8];
for (int i = 0; i < 8; i++)
{
int idx = (i + offset) % 8;
buff[i] = teeth[idx];
}
for (int i = 0; i < 8; i++)
{
teeth[i] = buff[i];
}
}
int n;
Gear gears[4];
void operateGears(int gearNo, bool direction, bool rotated[])
{
/*
현재 기어를 돌리기 전에 양 옆의 기어를 확인하고
현재 기어를 회전 한 후 양 옆의 기어를 operateGears 해준다
*/
bool g_right = false;
bool g_left = false;
if (gearNo + 1 < 4 && gears[gearNo + 1].teeth[6] != gears[gearNo].teeth[2] && !rotated[gearNo + 1])
{
g_right = true;
}
if (gearNo - 1 >= 0 && gears[gearNo - 1].teeth[2] != gears[gearNo].teeth[6] && !rotated[gearNo - 1])
{
g_left = true;
}
gears[gearNo].rotate(direction);
rotated[gearNo] = true;
if (g_right)
{
operateGears(gearNo + 1, !direction, rotated);
}
if (g_left)
{
operateGears(gearNo - 1, !direction, rotated);
}
}
int countGearScore()
{
int ret = 0;
for (int i = 0; i < 4; i++)
{
if (gears[i].teeth[0])
{
ret += pow(2, i);
}
}
return ret;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 8; j++)
{
char input;
cin >> input;
bool tp = (input == '1') ? true:false;
gears[i].teeth[j] = tp;
}
}
cin >> n;
while (n--)
{
int cmd_gearNo;
int cmd_direction;
bool rotated_gear[4] = {
false,
};
cin >> cmd_gearNo >> cmd_direction;
bool dir = (cmd_direction == 1) ? true : false;
operateGears(cmd_gearNo-1, dir, rotated_gear);
}
cout << countGearScore() << '\n';
return 0;
}
|
#include "monaffichage.h"
#include "ui_monaffichage.h"
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QPixmap>
monaffichage::monaffichage(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::monaffichage)
{
ui->setupUi(this);
QGraphicsScene * ma_scene;
ma_scene = new QGraphicsScene();
QGraphicsPixmapItem * mon_item;
mon_item = new QGraphicsPixmapItem();
QPixmap * mon_image = new QPixmap(":neutre.jpg");
mon_item->setPixmap(* mon_image);
ma_scene->addItem(mon_item);
ui->ma_vue->setScene(ma_scene);
}
monaffichage::~monaffichage()
{
delete ui;
}
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long t,i,m,arr[100000],j=0,k;
scanf("%lld",&t);
while(j<t){
scanf("%lld",&m);
for(i=0;i<m;i++){
scanf("%lld",&arr[i]);
}
k=arr[0];
for(i=0;i<m;i++){
if(arr[i]>k) k=arr[i];
}
printf("Case %lld: %lld\n",j+1,k);
j++;
}
return 0;
}
|
#include <gmp_lib/WSoG/WSoG.h>
#include <gmp_lib/trainMethods/LeastSquares.h>
#include <gmp_lib/trainMethods/LWR.h>
namespace as64_
{
namespace gmp_
{
double WSoG::zero_tol = 1e-200;
double WSoG::sigma_eps = 1e-3;
// ===================================
// ======= Public Functions ========
// ===================================
WSoG::WSoG(unsigned N_kernels, double kernel_std_scaling)
{
#ifdef WSoG_DEBUG_
try{
#endif
this->N_kernels = N_kernels;
this->w = arma::vec(this->N_kernels);
this->c = arma::linspace<arma::vec>(0,N_kernels-1, N_kernels)/(N_kernels-1);
double hi = 1 / std::pow(kernel_std_scaling*(this->c(1)-this->c(0)),2);
this->h = arma::vec().ones(this->N_kernels) * hi;
this->f0_d = 0;
this->fg_d = 1;
this->f0 = this->f0_d;
this->setFinalValue(this->fg_d);
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::WSoG]: ") + e.what()); }
#endif
}
int WSoG::numOfKernels() const
{
#ifdef WSoG_DEBUG_
try{
#endif
return this->w.size();
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::numOfKernels]: ") + e.what()); }
#endif
}
void WSoG::setStartValue(double f0)
{
#ifdef WSoG_DEBUG_
try{
#endif
this->f0 = f0;
this->calcSpatialScaling();
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::setStartValue]: ") + e.what()); }
#endif
}
void WSoG::setFinalValue(double fg)
{
#ifdef WSoG_DEBUG_
try{
#endif
this->fg = fg;
this->calcSpatialScaling();
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::setFinalValue]: ") + e.what()); }
#endif
}
double WSoG::getStartValue() const
{
return this->f0;
}
double WSoG::getFinalValue() const
{
return this->fg;
}
double WSoG::getSpatialScaling() const
{
return this->spat_s;
}
// =============================================================
void WSoG::train(const std::string &train_method, const arma::rowvec &x, const arma::rowvec &Fd, double *train_err)
{
#ifdef WSoG_DEBUG_
try{
#endif
int n_data = x.size();
arma::rowvec s = arma::rowvec().ones(n_data);
arma::mat Psi(this->N_kernels, n_data);
for (int i=0; i<n_data; i++) Psi.col(i) = this->kernelFun(x(i));
if ( train_method.compare("LS") == 0 ) this->w = leastSquares(Psi, s, Fd, this->zero_tol);
else if ( train_method.compare("LWR") == 0 ) this->w = localWeightRegress(Psi, s, Fd, this->zero_tol);
else throw std::runtime_error("[GMP_::train]: Unsupported training method");
this->f0_d = arma::dot(this->regressVec(0),this->w);
this->fg_d = arma::dot(this->regressVec(1),this->w);
this->setStartValue(this->f0_d);
this->setFinalValue(this->fg_d);
if (train_err)
{
arma::rowvec F(Fd.size());
for (int i=0; i<F.size(); i++) F(i) = this->output(x(i));
*train_err = arma::norm(F-Fd)/F.size();
}
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::train]: ") + e.what()); }
#endif
}
// =============================================================
double WSoG::output(double x) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec Phi = this->regressVec(x);
double f = arma::dot(Phi,this->w) - this->spat_s*this->f0_d + this->f0;
return f;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::output]: ") + e.what()); }
#endif
}
double WSoG::outputDot(double x, double dx) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec Phi_dot = this->regressVecDot(x,dx);
double f_dot = arma::dot(Phi_dot,this->w);
return f_dot;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::outputDot]: ") + e.what()); }
#endif
}
double WSoG::outputDDot(double x, double dx, double ddx) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec Phi_ddot = this->regressVecDDot(x, dx, ddx);
double f_ddot = arma::dot(Phi_ddot, this->w);
return f_ddot;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::outputDDot]: ") + e.what()); }
#endif
}
double WSoG::output3Dot(double x, double dx, double ddx, double d3x) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec Phi_3dot = this->regressVec3Dot(x, dx, ddx, d3x);
double f_3dot = arma::dot(Phi_3dot, this->w);
return f_3dot;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::output3Dot]: ") + e.what()); }
#endif
}
// =============================================================
void WSoG::updatePos(double x, double p, double sigma_p)
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::mat H = this->regressVec(x).t();
double p_hat = this->output(x);
double e = p - p_hat;
this->updateWeights(H, arma::vec({e}), arma::mat({sigma_p}));
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::updatePos]: ") + e.what()); }
#endif
}
void WSoG::updateVel(double x, double dx, double v, double sigma_v)
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::mat H = this->regressVecDot(x, dx).t();
arma::vec v_hat = H*this->w;
arma::vec e = arma::vec({v}) - v_hat;
this->updateWeights(H, e, arma::mat({sigma_v}));
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::updateVel]: ") + e.what()); }
#endif
}
void WSoG::updateAccel(double x, double dx, double ddx, double a, double sigma_a)
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::mat H = this->regressVecDDot(x, dx, ddx).t();
arma::vec a_hat = H*this->w;
arma::vec e = arma::vec({a}) - a_hat;
this->updateWeights(H, e, arma::mat({sigma_a}));
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::updateAccel]: ") + e.what()); }
#endif
}
void WSoG::updatePosVel(double x, double dx, double p, double v, const arma::vec &sigma_pv)
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::mat H = arma::join_vert(this->regressVec(x).t(), this->regressVecDot(x, dx).t());
double p_hat = this->output(x);
double v_hat = this->outputDot(x, dx);
arma::vec e = arma::vec({p, v}) - arma::vec({p_hat, v_hat});
this->updateWeights(H, e, arma::diagmat(sigma_pv));
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::updatePosVel]: ") + e.what()); }
#endif
}
void WSoG::updatePosAccel(double x, double dx, double ddx, double p, double a, const arma::vec &sigma_pa)
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::mat H = arma::join_vert(this->regressVec(x).t(), this->regressVecDDot(x, dx, ddx).t());
double p_hat = this->output(x);
double a_hat = this->outputDDot(x, dx, ddx);
arma::vec e = arma::vec({p, a}) - arma::vec({p_hat, a_hat});
this->updateWeights(H, e, arma::diagmat(sigma_pa));
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::updatePosAccel]: ") + e.what()); }
#endif
}
void WSoG::updateVelAccel(double x, double dx, double ddx, double v, double a, const arma::vec &sigma_va)
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::mat H = arma::join_vert(this->regressVecDot(x, dx).t(), this->regressVecDDot(x, dx, ddx).t());
arma::vec va_hat = H*this->w;
arma::vec e = arma::vec({v, a}) - va_hat;
this->updateWeights(H, e, arma::diagmat(sigma_va));
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::updateVelAccel]: ") + e.what()); }
#endif
}
void WSoG::updatePosVelAccel(double x, double dx, double ddx, double p, double v, double a, const arma::vec &sigma_pva)
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::mat H(3, this->N_kernels);
H.row(0) = this->regressVec(x).t();
H.row(1) = this->regressVecDot(x, dx).t();
H.row(2) = this->regressVecDDot(x, dx, ddx).t();
arma::vec pva_hat = H*this->w;
pva_hat(0) += -this->spat_s*this->f0_d + this->f0;
arma::vec e = arma::vec({p, v, a}) - pva_hat;
this->updateWeights(H, e, arma::diagmat(sigma_pva));
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::updatePosVelAccel]: ") + e.what()); }
#endif
}
void WSoG::updateWeights(const arma::mat &H, const arma::vec &e, const arma::mat &Sigma_z)
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::mat Sigma_w = arma::mat().eye(this->N_kernels, this->N_kernels);
// arma::mat K = arma::solve( (Sigma_z + H*Sigma_w*H.t()).t(), (Sigma_w*H.t()).t() , arma::solve_opts::fast+arma::solve_opts::likely_sympd).t();
arma::mat K = arma::solve( (Sigma_z + H*Sigma_w*H.t()), H*Sigma_w , arma::solve_opts::fast+arma::solve_opts::likely_sympd).t();
this->w = this->w + K*e;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::updateWeights]: ") + e.what()); }
#endif
}
// =============================================================
arma::vec WSoG::regressVec(double x) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec psi = this->kernelFun(x);
arma::vec phi = this->spat_s * psi / (arma::sum(psi) + this->zero_tol);
return phi;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::regressVec]: ") + e.what()); }
#endif
}
arma::vec WSoG::regressVecDot(double x, double dx) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec psi = this->kernelFun(x);
arma::vec psi_dot = this->kernelFunDot(x, dx);
double sum_psi = arma::sum(psi);
double sum_psi_dot = arma::sum(psi_dot);
arma::vec phi = psi / ( arma::sum(sum_psi) + this->zero_tol );
arma::vec phi_dot = this->spat_s * ( psi_dot - phi*sum_psi_dot ) / ( sum_psi + this->zero_tol);
return phi_dot;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::regressVecDot]: ") + e.what()); }
#endif
}
arma::vec WSoG::regressVecDDot(double x, double dx, double ddx) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec psi = this->kernelFun(x);
arma::vec psi_dot = this->kernelFunDot(x, dx);
arma::vec psi_ddot = this->kernelFunDDot(x, dx, ddx);
double sum_psi = arma::sum(psi);
double sum_psi_dot = arma::sum(psi_dot);
double sum_psi_ddot = arma::sum(psi_ddot);
arma::vec phi = psi / ( arma::sum(sum_psi) + this->zero_tol );
arma::vec phi_dot = ( psi_dot - phi*sum_psi_dot ) / ( sum_psi + this->zero_tol);
arma::vec phi_ddot = this->spat_s * (psi_ddot - 2*phi_dot*sum_psi_dot - phi*sum_psi_ddot) / ( sum_psi + this->zero_tol);
return phi_ddot;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::regressVecDDot]: ") + e.what()); }
#endif
}
arma::vec WSoG::regressVec3Dot(double x, double dx, double ddx, double d3x) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec psi = this->kernelFun(x);
arma::vec psi_dot = this->kernelFunDot(x, dx);
arma::vec psi_ddot = this->kernelFunDDot(x, dx, ddx);
arma::vec psi_3dot = this->kernelFun3Dot(x, dx, ddx, d3x);
double sum_psi = arma::sum(psi);
double sum_psi_dot = arma::sum(psi_dot);
double sum_psi_ddot = arma::sum(psi_ddot);
double sum_psi_3dot = arma::sum(psi_3dot);
arma::vec phi = psi / ( arma::sum(sum_psi) + this->zero_tol );
arma::vec phi_dot = ( psi_dot - phi*sum_psi_dot ) / ( sum_psi + this->zero_tol);
arma::vec phi_ddot = (psi_ddot - 2*phi_dot*sum_psi_dot - phi*sum_psi_ddot) / ( sum_psi + this->zero_tol);
arma::vec phi_3dot = this->spat_s * (psi_3dot - 3*phi_ddot*sum_psi_dot - 3*phi_dot*sum_psi_ddot - phi*sum_psi_3dot) / ( sum_psi + this->zero_tol);
return phi_3dot;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::regressVec3Dot]: ") + e.what()); }
#endif
}
// =============================================================
// ======================================
// ======= Protected Functions ========
// ======================================
void WSoG::calcSpatialScaling()
{
this->spat_s = (this->fg - this->f0) / (this->fg_d - this->f0_d);
}
// =============================================================
arma::vec WSoG::kernelFun(double x) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec psi = arma::exp(-this->h % (arma::pow(x-this->c,2)));
return psi;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::kernelFun]: ") + e.what()); }
#endif
}
arma::vec WSoG::kernelFunDot(double x, double dx) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec psi = this->kernelFun(x);
arma::vec a = (x-this->c)*dx;
arma::vec psi_dot = -2 * this->h % ( psi % a );
return psi_dot;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::kernelFunDot]: ") + e.what()); }
#endif
}
arma::vec WSoG::kernelFunDDot(double x, double dx, double ddx) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec psi = this->kernelFun(x);
arma::vec psi_dot = this->kernelFunDot(x, dx);
arma::vec a = (x-this->c)*dx;
arma::vec a_dot = (x-this->c)*ddx + std::pow(dx,2);
arma::vec psi_ddot = -2*this->h%( psi_dot%a + psi%a_dot );
return psi_ddot;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::kernelFunDDot]: ") + e.what()); }
#endif
}
arma::vec WSoG::kernelFun3Dot(double x, double dx, double ddx, double d3x) const
{
#ifdef WSoG_DEBUG_
try{
#endif
arma::vec psi = this->kernelFun(x);
arma::vec psi_dot = this->kernelFunDot(x, dx);
arma::vec psi_ddot = this->kernelFunDDot(x, dx, ddx);
arma::vec a = (x-this->c)*dx;
arma::vec a_dot = (x-this->c)*ddx + std::pow(dx,2);
arma::vec a_ddot = (x-this->c)*d3x + 3*dx*ddx;
arma::vec psi_3dot = -2*this->h%( psi_ddot%a + 2*psi_dot%a_dot + psi%a_ddot );
return psi_3dot;
#ifdef WSoG_DEBUG_
}catch(std::exception &e) { throw std::runtime_error(std::string("[WSoG::kernelFun3Dot]: ") + e.what()); }
#endif
}
} // namespace gmp_
} // namespace as64_
|
/* XMRig
* Copyright (c) 2002-2006 Hugo Weber <address@hidden>
* Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "hw/dmi/DmiReader.h"
#include "hw/dmi/DmiTools.h"
#include <windows.h>
namespace xmrig {
/*
* Struct needed to get the SMBIOS table using GetSystemFirmwareTable API.
*/
struct RawSMBIOSData {
uint8_t Used20CallingMethod;
uint8_t SMBIOSMajorVersion;
uint8_t SMBIOSMinorVersion;
uint8_t DmiRevision;
uint32_t Length;
uint8_t SMBIOSTableData[];
};
} // namespace xmrig
bool xmrig::DmiReader::read()
{
const uint32_t size = GetSystemFirmwareTable('RSMB', 0, nullptr, 0);
auto smb = reinterpret_cast<RawSMBIOSData *>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size));
if (!smb) {
return false;
}
if (GetSystemFirmwareTable('RSMB', 0, smb, size) != size) {
HeapFree(GetProcessHeap(), 0, smb);
return false;
}
m_version = (smb->SMBIOSMajorVersion << 16) + (smb->SMBIOSMinorVersion << 8) + smb->DmiRevision;
m_size = smb->Length;
return decode(smb->SMBIOSTableData, [smb]() {
HeapFree(GetProcessHeap(), 0, smb);
});
}
|
#define uno once
#pragma uno
#include "InputManager.h"
namespace Sonar
{
bool InputManager::IsSpriteClicked(const sf::Sprite& object, sf::Mouse::Button button, const sf::RenderWindow & window) const
{
if(!sf::Mouse::isButtonPressed(button))
return false;
const auto mousePosition = GetMousePosition(window);
return object.getGlobalBounds().contains(sf::Vector2f(mousePosition));
}
sf::Vector2i InputManager::GetMousePosition(const sf::RenderWindow & window) const
{
return sf::Mouse::getPosition(window);
}
}
|
#include "../../src/includes/test.hpp"
BEGIN_TEST
DESCRIBE("TEST")
IT("1=1")
int nbr = 1;
SHOULD(int, nbr).BE(1);
END_IT
IT("1=2")
int nbr = 1;
SHOULD(int, nbr).BE(2);
END_IT
IT("1!=3")
int nbr = 1;
SHOULD(int, nbr).NOT.BE(2);
END_IT
IT("BE_NULL")
int* nbr = nullptr;
SHOULD(int, nbr).BE_NULL;
END_IT
IT("BE_NOT_NULL")
int i = 1;
int* nbr = &i;
SHOULD(int, nbr).NOT.BE_NULL;
END_IT
IT("SHOULD_CONDITION")
SHOULD_CONDITION(1==2).BE_FALSE;
SHOULD_CONDITION(1==1).BE_TRUE;
END_IT
END_DESCRIBE
END_TEST
|
// Created on: 1994-11-16
// Created by: Marie Jose MARTZ
// Copyright (c) 1994-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 _GeomToIGES_GeomPoint_HeaderFile
#define _GeomToIGES_GeomPoint_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <GeomToIGES_GeomEntity.hxx>
class IGESGeom_Point;
class Geom_Point;
class Geom_CartesianPoint;
//! This class implements the transfer of the Point Entity from Geom
//! to IGES . These are :
//! . Point
//! * CartesianPoint
class GeomToIGES_GeomPoint : public GeomToIGES_GeomEntity
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT GeomToIGES_GeomPoint();
//! Creates a tool GeomPoint ready to run and sets its
//! fields as GE's.
Standard_EXPORT GeomToIGES_GeomPoint(const GeomToIGES_GeomEntity& GE);
//! Transfert a Point from Geom to IGES. If this
//! Entity could not be converted, this member returns a NullEntity.
Standard_EXPORT Handle(IGESGeom_Point) TransferPoint (const Handle(Geom_Point)& start);
//! Transfert a CartesianPoint from Geom to IGES. If this
//! Entity could not be converted, this member returns a NullEntity.
Standard_EXPORT Handle(IGESGeom_Point) TransferPoint (const Handle(Geom_CartesianPoint)& start);
protected:
private:
};
#endif // _GeomToIGES_GeomPoint_HeaderFile
|
const float color[7][3] = { // identifyZone()用の固定値
{90, 85, 28},
{52, 20, 35},
{21, 53, 62},
{57, 8, 4},
{13, 43, 15},
{2, 10, 35},
{13, 20, 46}
};
float minDistance; // identifyZone()用のグローバル変数
// startからzoneへの移動(zone番号の認識もする)
void startToZone()
{
int zoneNumber;
int done;
switch ( mode_G ) {
case 0: // setupが必要ならここ(必要が無くても形式的に)
mode_G = 1;
break;
case 1: // ライントレース(黄と黒の混合色を検知するまで)
linetracePID();
done = identifyColor( 2 );
if ( done == 1 ) {
mode_G = 2;
}
break;
case 2: // 黒を検知するまで直進
goStraight();
done = identifyColor( 0 );
if ( done == 1 )
mode_G = 3;
break;
case 3: // identifyZone()のsetup
minDistance = 9999999;
mode_G = 4;
break;
case 4: // 白を検知するまで直進(その間ゾーン番号を検知)
goStraight();
zoneNumber = identifyZone();
done = identifyColor( 1 );
if ( done == 1 ) {
zoneNumber_G = zoneNumber;
mode_G = 0;
}
break;
default:
break;
}
}
// zoneからzoneへの移動(zone番号の認識もする)
void zoneToZone()
{
// 各自で作成
int zoneNumber;
int done;
switch ( mode_G ) {
case 0: // setupが必要ならここ(必要が無くても形式的に)
mode_G = 1;
break;
case 1: // ライントレース(黄と黒の混合色を検知するまで)
linetracePID();
done = identifyColor( 2 );
if ( done == 1 ) {
mode_G = 2;
}
break;
case 2: // 白を検知するまで
goStraight();
done = identifyColor( 1 );
if ( done == 1 )
mode_G = 3;
break;
case 3: // ライントレース(黄と黒の混合色を検知するまで)
linetracePID();
done = identifyColor( 2 );
if ( done == 1 ) {
mode_G = 4;
}
break;
case 4: // 黒を検知するまで直進
goStraight();
done = identifyColor( 0 );
if ( done == 1 )
mode_G = 5;
break;
case 5: // identifyZone()のsetup
minDistance = 9999999;
mode_G = 6;
break;
case 6: // 白を検知するまで直進(その間ゾーン番号を検知)
goStraight();
zoneNumber = identifyZone();
done = identifyColor( 1 );
if ( done == 1 ) {
zoneNumber_G = zoneNumber;
mode_G = 0;
}
break;
default:
break;
}
}
// 直進する
void goStraight()
{
motorL_G = SPEED;
motorR_G = SPEED;
}
void goStraight6()
{
motorL_G = 100;
motorR_G =100;
}
// 黒白の境界に沿ってライントレース
void linetracePID()
{
static unsigned long timePrev = 0;
static float lightPrevPD = 0.0;
float lightNowPD;
float error, errorSP;
float diff, diffSP;
float speedDiff;
float target = 50;
float Kp = 1.5;
float Kd = 1.5;
lightNowPD = ( red_G + green_G + blue_G ) / 3.0;
error = lightNowPD - target;
errorSP = map(error, -target, target, -SPEED, SPEED );
diff = (lightNowPD - lightPrevPD) / (timeNow_G - timePrev );
diffSP = map(diff, -100.0, 100.0, -SPEED, SPEED );
speedDiff = Kp * errorSP + Kd * diffSP;
/*
motorL_G = SPEED - speedDiff;
motorR_G = SPEED + speedDiff;
*/
if (speedDiff > 0) {
motorL_G = SPEED - speedDiff;
motorR_G = SPEED;
}
else {
motorL_G = SPEED;
motorR_G = SPEED + speedDiff;
}
timePrev = timeNow_G;
lightPrevPD = lightNowPD;
}
// 指定の色を連続4回認識したら1を返す(それ以外0)
int identifyColor( int color )
{
static int count = 0; // この関数が初めて呼ばれた時にのみ初期化される
if ( color == 0 && red_G < 25 && green_G < 25 && blue_G < 25 ) // 黒を感知
++count;
else if ( color == 1 && red_G > 75 && green_G > 75 && blue_G > 75 ) // 白を感知
++count;
else if ( color == 2 && ( red_G + green_G ) / 2.0 * 0.7 > blue_G && ( red_G + green_G ) * 0.5 > 30 ) // 黄黒の混合色を感知
++count;
else if (color == 3 && red_G < 15 && green_G < 25 && blue_G < 60 && blue_G > 30){
count = 4;
}
else
count = 0;
if ( count > 3 ) { // パラメーター
count = 0; // 次に呼ばれる時に備えて値を初期値に戻す
return 1;
}
else
return 0;
}
// KNNで現在最も近い番号を返す
int identifyZone()
{
// float minDistance; グローバル変数で定義
static int zoneNumber;
float distance;
for ( int i = 0; i < 7; ++i ) {
distance = (red_G - color[i][0]) * (red_G - color[i][0])
+ (green_G - color[i][1]) * (green_G - color[i][1])
+ (blue_G - color[i][2]) * (blue_G - color[i][2]);
if ( distance < minDistance ) {
minDistance = distance;
zoneNumber = i;
}
}
return zoneNumber + 1; // zone番号は1-7なので+1
}
void linetracePID6()
{
static unsigned long timePrev = 0;
static float lightPrevPD = 0.0;
float lightNowPD;
float error, errorSP;
float diff, diffSP;
float speedDiff;
float target = 60;
float Kp = 2.7;
float Kd = 1.5;
lightNowPD = (red_G + green_G + blue_G) / 3.0;
error = lightNowPD - target;
// errorSP = map(error, -target, target, -SPEED, SPEED );
int lightNowPD_MIN = 12;
int lightNowPD_MAX = 85;
errorSP = map(lightNowPD, lightNowPD_MIN, lightNowPD_MAX, -SPEED, SPEED );
diff = (lightNowPD - lightPrevPD) / (timeNow_G - timePrev );
diffSP = map(diff, -100.0, 100.0, -SPEED, SPEED );
speedDiff = Kp * errorSP + Kd * diffSP;
if (speedDiff > 0) {
motorL_G = SPEED - speedDiff;
motorR_G = SPEED;
}
else {
motorL_G = SPEED;
motorR_G = SPEED + speedDiff;
}
timePrev = timeNow_G;
lightPrevPD = lightNowPD;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2011 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"
#include "adjunct/desktop_util/resources/pi/opdesktopproduct.h"
#include "modules/prefsfile/prefsfile.h"
/*static*/
OP_STATUS OpDesktopProduct::GetProductInfo(OperaInitInfo*, PrefsFile* operaprefs, OpDesktopProduct::ProductInfo& product_info)
{
const DesktopProductType pref_to_enum_map[] =
{
PRODUCT_TYPE_OPERA,
PRODUCT_TYPE_OPERA_NEXT,
PRODUCT_TYPE_OPERA_LABS
};
int pref;
RETURN_IF_LEAVE(pref = operaprefs->ReadIntL("System", "Opera Product"));
//No guarantee that the value of the pref is valid, since it can be changed by users
if (pref >= (sizeof(pref_to_enum_map)/sizeof(DesktopProductType)) || pref < 0)
{
product_info.m_product_type = PRODUCT_TYPE_OPERA;
}
else
{
product_info.m_product_type = pref_to_enum_map[pref];
}
if (product_info.m_product_type == PRODUCT_TYPE_OPERA_LABS)
{
RETURN_IF_LEAVE(operaprefs->ReadStringL("System", "Opera Labs Name", product_info.m_labs_product_name));
}
else
{
product_info.m_labs_product_name.Empty();
}
return product_info.m_package_type.Set("exe");
}
|
#include "parametersettingwindow.h"
#include "ui_parametersettingwindow.h"
#include "externdata.h"
#include <QMessageBox>
#include <QDebug>
ParameterSettingWindow::ParameterSettingWindow(QWidget *parent) :
QDialog(parent),
ui(new Ui::ParameterSettingWindow)
{
ui->setupUi(this);
this->setFixedSize(420,725);
this->setWindowTitle("通道参数设置");
edit1 = ui->layoutWidget_3->findChildren<QLineEdit*>(); //获取ON/OFF输入框
edit2 = ui->layoutWidget_2->findChildren<QLineEdit*>(); //获取占空比输入框
for(QList<QLineEdit*>::size_type i=0; i!=edit1.size(); i++){
edit1.at(i)->setValidator(new QIntValidator(0,MAXTIME,this));
}
for(QList<QLineEdit*>::size_type i=0; i!=edit2.size(); i++){
edit2.at(i)->setValidator(new QIntValidator(0,100,this));
}
ui->lineEdit_duty->setValidator(new QIntValidator(0,100,this));
ui->lineEdit_freq5->setValidator(new QIntValidator(0,MAXFREQ5,this));
ui->lineEdit_freq6->setValidator(new QIntValidator(0,MAXFREQ6,this));
ui->lineEdit0->setEnabled(false);
connect(ui->spinBox_0,SIGNAL(valueChanged(int)),this,SLOT(slotSpinBoxChange()));
connect(ui->spinBox_1,SIGNAL(valueChanged(int)),this,SLOT(slotEditShow()));
}
ParameterSettingWindow::~ParameterSettingWindow()
{
delete ui;
}
void ParameterSettingWindow::slotSpinBoxChange()
{
if(ui->spinBox_0->value() != 0){
ui->label_1->setText("第"+QString::number(ui->spinBox_0->value())+"周期");
ui->lineEdit0->setText(QString::number(everyCycleTime[ui->spinBox_0->value()-1],10));
everycycledata[this->pFlag-1][ui->spinBox_0->value()-1].onCount = ui->spinBox_1->value();
for(int8_t i=0; i<everycycledata[this->pFlag-1][ui->spinBox_0->value()-1].onCount; i++){
everycycledata[this->pFlag-1][ui->spinBox_0->value()-1].onTime[i][0] = edit1.at(2*i)->text().toInt();
everycycledata[this->pFlag-1][ui->spinBox_0->value()-1].onTime[i][1] = edit1.at(2*i+1)->text().toInt();
if(this->pFlag == 6){
pwmDuty[ui->spinBox_0->value()-1][i] = edit2.at(i)->text().toInt();
}
}
}
for(int8_t i=0; i<edit1.size(); i++)
edit1.at(i)->setText("36000000");
for(int8_t i=0; i<edit2.size(); i++)
edit2.at(i)->setText("36000000");
}
///
void ParameterSettingWindow::on_pushButton_clicked()
{
QMessageBox::StandardButton button;
button = QMessageBox::question(this,"关闭提示",QString("确认设置?"),QMessageBox::Yes|QMessageBox::No);
if(button == QMessageBox::No){
}
else if(button == QMessageBox::Yes){
if(this->pFlag == 5){
turnDuty = ui->lineEdit_duty->text().toInt();
turnFreq = ui->lineEdit_freq5->text().toInt();
qDebug()<<"占空比:"<<turnDuty<<"频率:"<<turnFreq;
}
else if(this->pFlag == 6){
pwmFreq = ui->lineEdit_freq6->text().toInt();
qDebug()<<"频率:"<<pwmFreq;
}
this->close();
}
}
void ParameterSettingWindow::on_pushButton_2_clicked()
{
this->close();
}
void ParameterSettingWindow::setFlag(int8_t x)
{
this->pFlag = x;
}
void ParameterSettingWindow::setName()
{
if(this->pFlag<=4)
ui->label->setText("通道"+QString::number(this->pFlag));
else if(this->pFlag == 5)
ui->label->setText("转向灯通道");
else if(this->pFlag == 6)
ui->label->setText("PWM通道");
}
void ParameterSettingWindow::refresh()
{
ui->lineEdit0->setText(QString::number(everyCycleTime[ui->spinBox_0->value()-1]));
ui->spinBox_0->setMaximum(allCycle);
if(this->pFlag<5){
ui->layoutWidget_2->hide();
ui->layoutWidget_9->hide();
ui->layoutWidget_7->hide();
ui->layoutWidget_4->hide();
}
else if(this->pFlag == 5){
ui->layoutWidget_9->show();
ui->layoutWidget_4->show();
ui->layoutWidget_2->hide();
ui->layoutWidget_7->hide();
}
else if(this->pFlag == 6){
ui->layoutWidget_2->show();
ui->layoutWidget_7->show();
ui->layoutWidget_9->hide();
ui->layoutWidget_4->hide();
}
for(int8_t i=0; i<edit1.size(); i++)
edit1.at(i)->setText("0");
for(int8_t i=0; i<edit2.size(); i++)
edit2.at(i)->setText("0");
ui->spinBox_0->setValue(0);
ui->spinBox_1->setValue(20);
}
void ParameterSettingWindow::slotEditShow()
{
for(QList<QLineEdit*>::size_type i=0; i!=edit1.size(); i++){
if(i<ui->spinBox_1->value()*2)
edit1.at(i)->setEnabled(true);
else
edit1.at(i)->setEnabled(false);
}
for(QList<QLineEdit*>::size_type i=0; i!=edit2.size(); i++){
if(i<ui->spinBox_1->value())
edit2.at(i)->setEnabled(true);
else
edit2.at(i)->setEnabled(false);
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define TESTC ""
#define PROBLEM "10534"
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 10000
int NUM[MAXN+5],LIS[MAXN+5],LDS[MAXN+5];
int main(int argc, char const *argv[])
{
#ifdef DBG
freopen("uva" PROBLEM TESTC ".in", "r", stdin);
freopen("uva" PROBLEM ".out", "w", stdout);
#endif
int num,len;
vector <int> table;
while( ~scanf("%d",&num) ){
for(int i = 0 ; i < num ; i++ )
scanf("%d",&NUM[i]);
table.clear();
table.push_back(NUM[0]);
LIS[0] = len = 1;
for(int i = 1 ; i < num ; i++ ){
if( NUM[i] > table.back() ){
table.push_back(NUM[i]);
LIS[i] = ++len;
}
else{
*lower_bound(table.begin(), table.end(),NUM[i]) = NUM[i];
LIS[i] = lower_bound(table.begin(), table.end(),NUM[i])-table.begin() + 1;
}
}
table.clear();
table.push_back(NUM[num-1]);
LDS[num-1] = len = 1;
for(int i = num-2 ; i >= 0 ; i-- ){
if( NUM[i] > table.back() ){
table.push_back(NUM[i]);
LDS[i] = ++len;
}
else{
*lower_bound(table.begin(), table.end(),NUM[i]) = NUM[i];
LDS[i] = lower_bound(table.begin(), table.end(),NUM[i])-table.begin() + 1;
}
}
int MAX = 0;
for(int i = 0 ; i < num ; i++ ){
int tmp = min(LIS[i],LDS[i]);
if( MAX < tmp )
MAX = tmp;
}
printf("%d\n",MAX*2-1 );
}
return 0;
}
|
/*
Copyright (c) 2015-2022 Xavier Leclercq
Released under the MIT License
See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt
*/
#include "FilesTeardownAction.hpp"
#include <boost/filesystem/operations.hpp>
namespace Ishiko
{
void FilesTeardownAction::teardown()
{
for (size_t i = 0; i < d_files.size(); ++i)
{
boost::filesystem::remove(d_files[i]);
}
}
void FilesTeardownAction::add(const boost::filesystem::path& path)
{
d_files.push_back(path);
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef CSS_CHARSET_RULE_H
#define CSS_CHARSET_RULE_H
#include "modules/style/src/css_rule.h"
class CSS_CharsetRule : public CSS_Rule
{
public:
CSS_CharsetRule() : m_charset(0) {}
virtual ~CSS_CharsetRule() { OP_DELETEA(m_charset); }
virtual Type GetType() { return CHARSET; }
void SetCharset(uni_char* charset) { OP_DELETEA(m_charset); m_charset = charset; }
const uni_char* GetCharset() { return m_charset; }
virtual OP_STATUS GetCssText(CSS* stylesheet, TempBuffer* buf, unsigned int indent_level = 0);
virtual CSS_PARSE_STATUS SetCssText(HLDocProfile* hld_prof, CSS* stylesheet, const uni_char* text, int len);
private:
uni_char* m_charset;
};
#endif // CSS_CHARSET_RULE_H
|
// SPDX-FileCopyrightText: 2021 Samuel Cabrero <samuel@orica.es>
//
// SPDX-License-Identifier: MIT
#ifndef __LOG_H__
#define __LOG_H__
#include <Arduino.h>
class TLog {
public:
TLog();
void debug(const char *fmt, ...);
void info(const char *fmt, ...);
void error(const char *fmt, ...);
int count() const;
const char *getBuffer(int idx) const;
void clearBuffer();
private:
static const int BuffMsgLen = 128;
static const int BuffMsgNum = 64;
void log(const char *lvl, bool buffer, const char *fmt, va_list args);
char m_buffer[BuffMsgNum][BuffMsgLen];
int m_idx;
};
extern TLog Log;
#endif /* __LOG_H__ */
|
#ifndef parser_h
#define parser_h
#include <string>
class BlockParser {
int blocks_count = 0;
public:
enum Block {
StartBlock,
CancelBlock,
Command,
Empty
};
Block parsing(const std::string& line);
bool is_block = false;
};
int start_parsing(int argc, char *argv[], uint n);
#endif
|
/**************************************************************************/
/* */
/* Copyright (c) 2013-2022 Orbbec 3D Technology, Inc */
/* */
/* PROPRIETARY RIGHTS of Orbbec 3D Technology are involved in the */
/* subject matter of this material. All manufacturing, reproduction, use, */
/* and sales rights pertaining to this subject matter are governed by the */
/* license agreement. The recipient of this software implicitly accepts */
/* the terms of the license. */
/* */
/**************************************************************************/
#pragma once
#include <astra_camera/AstraConfig.h>
#include <camera_info_manager/camera_info_manager.h>
#include <cv_bridge/cv_bridge.h>
#include <dynamic_reconfigure/server.h>
#include <image_transport/image_transport.h>
#include <openni2/OpenNI.h>
#include <openni2/PS1080.h>
#include <ros/ros.h>
#include <sensor_msgs/CameraInfo.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/distortion_models.h>
#include <sensor_msgs/point_cloud2_iterator.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2/LinearMath/Transform.h>
#include <tf2/LinearMath/Vector3.h>
#include <tf2_ros/static_transform_broadcaster.h>
#include <tf2_ros/transform_broadcaster.h>
#include <boost/optional.hpp>
#include <condition_variable>
#include <mutex>
#include <opencv2/opencv.hpp>
#include <thread>
#include "constants.h"
#include "d2c_viewer.h"
#include "point_cloud_proc/point_cloud_proc.h"
#include "types.h"
#include "utils.h"
#include "uvc_camera_driver.h"
namespace astra_camera {
using ReconfigureServer = dynamic_reconfigure::Server<AstraConfig>;
class OBCameraNode {
public:
OBCameraNode(ros::NodeHandle& nh, ros::NodeHandle& nh_private,
std::shared_ptr<openni::Device> device, bool use_uvc_camera = false);
~OBCameraNode();
void clean();
void init();
private:
void setupCameraCtrlServices();
void setupConfig();
void setupCameraInfoManager();
void setupDevices();
void setupD2CConfig();
void setupFrameCallback();
void setupVideoMode();
void startStreams();
void stopStreams();
void startStream(const stream_index_pair& stream_index);
void stopStream(const stream_index_pair& stream_index);
void getParameters();
void setupTopics();
void setupUVCCamera();
void imageSubscribedCallback(const stream_index_pair& stream_index);
void imageUnsubscribedCallback(const stream_index_pair& stream_index);
void setupPublishers();
void publishStaticTF(const ros::Time& t, const tf2::Vector3& trans, const tf2::Quaternion& q,
const std::string& from, const std::string& to);
void calcAndPublishStaticTransform();
void publishDynamicTransforms();
void publishStaticTransforms();
void setImageRegistrationMode(bool data);
bool setMirrorCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response,
const stream_index_pair& stream_index);
bool getExposureCallback(GetInt32Request& request, GetInt32Response& response,
const stream_index_pair& stream_index);
bool setExposureCallback(SetInt32Request& request, SetInt32Response& response,
const stream_index_pair& stream_index);
bool getGainCallback(GetInt32Request& request, GetInt32Response& response,
const stream_index_pair& stream_index);
bool setGainCallback(SetInt32Request& request, SetInt32Response& response,
const stream_index_pair& stream_index);
int getIRExposure();
void setIRExposure(uint32_t data);
int getIRGain();
std::string getSerialNumber();
void setIRGain(int data);
bool resetIRGainCallback(std_srvs::EmptyRequest& request, std_srvs::EmptyResponse& response);
bool resetIRExposureCallback(std_srvs::EmptyRequest& request, std_srvs::EmptyResponse& response);
bool getAutoWhiteBalanceEnabledCallback(GetInt32Request& request, GetInt32Response& response,
const stream_index_pair& stream_index);
bool setAutoWhiteBalanceEnabledCallback(SetInt32Request& request, SetInt32Response& response);
bool setAutoExposureCallback(std_srvs::SetBoolRequest& request,
std_srvs::SetBoolResponse& response,
const stream_index_pair& stream_index);
bool setLaserEnableCallback(std_srvs::SetBoolRequest& request,
std_srvs::SetBoolResponse& response);
bool setIRFloodCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response);
bool setLdpEnableCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response);
bool setFanEnableCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response);
bool getDeviceInfoCallback(GetDeviceInfoRequest& request, GetDeviceInfoResponse& response);
bool getCameraInfoCallback(GetCameraInfoRequest& request, GetCameraInfoResponse& response);
bool getSDKVersionCallback(GetStringRequest& request, GetStringResponse& response);
bool getDeviceTypeCallback(GetStringRequest& request, GetStringResponse& response);
bool getSerialNumberCallback(GetStringRequest& request, GetStringResponse& response);
bool switchIRCameraCallback(SetStringRequest& request, SetStringResponse& response);
bool getCameraParamsCallback(GetCameraParamsRequest& request, GetCameraParamsResponse& response);
bool toggleSensorCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response,
const stream_index_pair& stream_index);
bool saveImagesCallback(std_srvs::EmptyRequest& request, std_srvs::EmptyResponse& response);
bool getSupportedVideoModesCallback(GetStringRequest& request, GetStringResponse& response,
const stream_index_pair& stream_index);
bool getLdpStatusCallback(GetBoolRequest& request, GetBoolResponse& response);
bool toggleSensor(const stream_index_pair& stream_index, bool enabled, std::string& msg);
void onNewFrameCallback(const openni::VideoFrameRef& frame,
const stream_index_pair& stream_index);
void setDepthColorSync(bool data);
void setDepthToColorResolution(int width, int height);
OBCameraParams getCameraParams();
static sensor_msgs::CameraInfo OBCameraParamsToCameraInfo(const OBCameraParams& params);
double getFocalLength(const stream_index_pair& stream_index, int y_resolution);
sensor_msgs::CameraInfo getIRCameraInfo(int width, int height, double f);
sensor_msgs::CameraInfo getDepthCameraInfo();
sensor_msgs::CameraInfo getColorCameraInfo();
sensor_msgs::CameraInfo getDefaultCameraInfo(int width, int height, double f);
boost::optional<openni::VideoMode> lookupVideoModeFromDynConfig(int index);
// NOTE: This interface only for testing purposes.
void reconfigureCallback(const AstraConfig& config, uint32_t level);
void sendKeepAlive(const ros::TimerEvent& event);
void pollFrame();
private:
ros::NodeHandle nh_;
ros::NodeHandle nh_private_;
std::shared_ptr<openni::Device> device_;
std::shared_ptr<UVCCameraDriver> uvc_camera_driver_ = nullptr;
std::string camera_name_ = "camera";
std::unique_ptr<ReconfigureServer> reconfigure_server_ = nullptr;
std::map<int, openni::VideoMode> video_modes_lookup_table_;
bool use_uvc_camera_ = false;
openni::DeviceInfo device_info_{};
std::atomic_bool is_running_{false};
std::map<stream_index_pair, bool> enable_;
std::map<stream_index_pair, bool> stream_started_;
std::map<stream_index_pair, int> width_;
std::map<stream_index_pair, int> height_;
std::map<stream_index_pair, int> fps_;
std::map<stream_index_pair, openni::PixelFormat> format_;
std::map<stream_index_pair, int> image_format_;
std::map<stream_index_pair, std::string> encoding_;
std::map<stream_index_pair, cv::Mat> images_;
std::vector<int> compression_params_;
std::string base_frame_id_;
std::map<stream_index_pair, std::string> frame_id_;
std::map<stream_index_pair, std::string> optical_frame_id_;
std::map<stream_index_pair, std::string> depth_aligned_frame_id_;
std::map<stream_index_pair, std::string> stream_name_;
std::map<stream_index_pair, std::shared_ptr<openni::VideoStream>> streams_;
std::map<stream_index_pair, openni::VideoMode> stream_video_mode_;
std::map<stream_index_pair, std::vector<openni::VideoMode>> supported_video_modes_;
std::map<stream_index_pair, FrameCallbackFunction> stream_frame_callback_;
std::map<stream_index_pair, int> unit_step_size_;
std::map<stream_index_pair, ros::Publisher> image_publishers_;
std::map<stream_index_pair, ros::Publisher> camera_info_publishers_;
std::map<stream_index_pair, ros::ServiceServer> get_exposure_srv_;
std::map<stream_index_pair, ros::ServiceServer> set_exposure_srv_;
std::map<stream_index_pair, ros::ServiceServer> get_gain_srv_;
std::map<stream_index_pair, ros::ServiceServer> set_gain_srv_;
std::map<stream_index_pair, ros::ServiceServer> set_mirror_srv_;
std::map<stream_index_pair, ros::ServiceServer> toggle_sensor_srv_;
std::map<stream_index_pair, ros::ServiceServer> get_supported_video_modes_srv_;
ros::ServiceServer get_sdk_version_srv_;
std::map<stream_index_pair, ros::ServiceServer> set_auto_exposure_srv_;
ros::ServiceServer get_device_srv_;
ros::ServiceServer set_laser_enable_srv_;
ros::ServiceServer set_ldp_enable_srv_;
ros::ServiceServer set_fan_enable_srv_;
ros::ServiceServer get_camera_info_srv_;
ros::ServiceServer switch_ir_camera_srv_;
ros::ServiceServer get_white_balance_srv_;
ros::ServiceServer set_white_balance_srv_;
ros::ServiceServer get_camera_params_srv_;
ros::ServiceServer get_device_type_srv_;
ros::ServiceServer get_serial_srv_;
ros::ServiceServer save_images_srv_;
ros::ServiceServer reset_ir_gain_srv_;
ros::ServiceServer reset_ir_exposure_srv_;
ros::ServiceServer set_ir_flood_srv_;
ros::ServiceServer get_ldp_status_srv_;
bool publish_tf_ = true;
std::shared_ptr<tf2_ros::StaticTransformBroadcaster> static_tf_broadcaster_;
std::shared_ptr<tf2_ros::TransformBroadcaster> dynamic_tf_broadcaster_;
std::vector<geometry_msgs::TransformStamped> static_tf_msgs_;
ros::Publisher extrinsics_publisher_;
std::shared_ptr<std::thread> tf_thread_;
std::condition_variable tf_cv_;
double tf_publish_rate_ = 10.0;
bool depth_align_ = false;
boost::optional<OBCameraParams> camera_params_;
double depth_ir_x_offset_ = 0.0;
double depth_ir_y_offset_ = 0.0;
bool color_depth_synchronization_ = false;
int depth_scale_ = 1;
ImageROI color_roi_;
ImageROI depth_roi_;
bool enable_reconfigure_ = false;
std::map<stream_index_pair, std::atomic_bool> save_images_;
std::recursive_mutex device_lock_;
int init_ir_gain_ = 0;
uint32_t init_ir_exposure_ = 0;
bool enable_d2c_viewer_ = false;
std::unique_ptr<D2CViewer> d2c_filter_ = nullptr;
std::unique_ptr<camera_info_manager::CameraInfoManager> color_info_manager_ = nullptr;
std::unique_ptr<camera_info_manager::CameraInfoManager> ir_info_manager_ = nullptr;
std::string ir_info_uri_;
std::string color_info_uri_;
bool keep_alive_ = false;
int keep_alive_interval_ = 15;
ros::Timer keep_alive_timer_;
std::atomic_bool initialized_{false};
std::unique_ptr<PointCloudXyzNode> point_cloud_xyz_node_ = nullptr;
std::unique_ptr<PointCloudXyzrgbNode> point_cloud_xyzrgb_node_ = nullptr;
bool enable_pointcloud_ = false;
bool enable_pointcloud_xyzrgb_ = false;
std::unique_ptr<std::thread> poll_frame_thread_ = nullptr;
std::atomic_bool run_poll_frame_thread_{false};
std::mutex poll_frame_thread_lock_;
std::condition_variable poll_frame_thread_cv_;
bool enable_publish_extrinsic_ = false;
};
} // namespace astra_camera
|
#ifndef _MAC_OP_SOUND_H_
#define _MAC_OP_SOUND_H_
#ifndef NO_CARBON
#include "platforms/mac/model/macthread.h"
#include "modules/util/simset.h"
#define Size MacSize
#define Style MacFontStyle
#include <QuickTime/QuickTime.h>
#undef Style
#undef Size
#if PRAGMA_STRUCT_ALIGN
#pragma options align=mac68k
#elif PRAGMA_STRUCT_PACKPUSH
#pragma pack(push, 2)
#elif PRAGMA_STRUCT_PACK
#pragma pack(2)
#endif
typedef struct {
AudioFormatAtom formatData;
AudioEndianAtom endianData;
AudioTerminatorAtom terminatorData;
} AudioCompressionAtom, *AudioCompressionAtomPtr, **AudioCompressionAtomHandle;
#if PRAGMA_STRUCT_ALIGN
#pragma options align=reset
#elif PRAGMA_STRUCT_PACKPUSH
#pragma pack(pop)
#elif PRAGMA_STRUCT_PACK
#pragma pack()
#endif
typedef struct {
ExtendedSoundComponentData compData;
Handle hSource; // source media buffer
Media sourceMedia; // sound media identifier
TimeValue getMediaAtThisTime;
TimeValue sourceDuration;
UInt32 maxBufferSize;
Boolean isThereMoreSource;
Boolean isSourceVBR;
} SCFillBufferData, *SCFillBufferDataPtr;
enum eBufferNumber { kFirstBuffer, kSecondBuffer };
class MacOpSound : protected MacThread, public Link
{
public:
virtual ~MacOpSound();
OP_STATUS Init();
static void Terminate();
OP_STATUS Play(BOOL async);
OP_STATUS Stop();
static MacOpSound* GetSound(const uni_char* fullpath);
private:
FSSpec m_SoundFile;
MPSemaphoreID m_BufferDoneSignalID;
MPSemaphoreID m_PlayingStoppedSignalID;
SndChannelPtr m_UsedChannel;
Boolean m_StopPlaying;
MacOpSound(FSSpec *spec);
virtual OSStatus run();
static MacOpSound* FindSoundForChannel(SndChannelPtr theChannel);
static pascal void OpSoundCallBackFunction(SndChannelPtr theChannel, SndCommand *theCmd);
static pascal Boolean SoundConverterFillBufferDataProc(SoundComponentDataPtr *outData, void *inRefCon);
static Boolean isQTinitialized;
static CGrafPtr suppressVideoOffscreen;
static Head theSounds;
};
#endif // NO_CARBON
#endif // _MAC_OP_SOUND_H_
|
/*
==============================================================================
blueprint.cpp
Created: 26 Nov 2018 3:19:03pm
==============================================================================
*/
#ifdef BLUEPRINT_H_INCLUDED
/* When you add this cpp file to your project, you mustn't include it in a file where you've
already included any other headers - just put it inside a file on its own, possibly with your config
flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix
header files that the compiler may be using.
*/
#error "Incorrect use of the Blueprint cpp file"
#endif
/* We're careful to include the duktape source files before the module header
* file because `duktape.c` sets certain preprocessor definitions that enable
* necessary features in the duktape header. We need those defines to preempt
* the loading of the duktape header. This also, therefore, is the place for
* custom preprocessor definitions.
*
* We force Duktape to use a time provider on Windows that is compatible with
* Windows 7 SP1. It looks like W7SP1 is quite happy with plugins built with
* the 8.1 SDK, but the GetSystemTimePreciseAsFileTime() call used in here is
* just not supported without the 8.1 dll available.
*/
#if defined (_WIN32) || defined (_WIN64)
#define DUK_USE_DATE_NOW_WINDOWS 1
#endif
// Disable compiler warnings for external source files (duktape & yoga)
#if _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4018) // signed/unsigned mismatch
#pragma warning(disable : 4127) // conditional expression is constant
#pragma warning(disable : 4505) // unreferenced local function
#pragma warning(disable : 4611) // object destruction is non-portable
#pragma warning(disable : 4702) // unreachable code
#endif
#include "duktape/src-noline/duktape.c"
#include "duktape/extras/console/duk_console.c"
#include "blueprint.h"
#include "yoga/yoga/log.cpp"
#include "yoga/yoga/Utils.cpp"
#include "yoga/yoga/YGConfig.cpp"
#include "yoga/yoga/YGEnums.cpp"
#include "yoga/yoga/YGLayout.cpp"
#include "yoga/yoga/YGNode.cpp"
#include "yoga/yoga/YGNodePrint.cpp"
#include "yoga/yoga/YGStyle.cpp"
#include "yoga/yoga/YGValue.cpp"
#include "yoga/yoga/Yoga.cpp"
// Enable compiler warnings
#if _MSC_VER
#pragma warning (pop)
#endif
#include "core/blueprint_EcmascriptEngine.cpp"
#include "core/blueprint_GenericEditor.cpp"
#include "core/blueprint_ReactApplicationRoot.cpp"
#include "core/blueprint_ShadowView.cpp"
#include "core/blueprint_TextShadowView.cpp"
#include "core/blueprint_View.cpp"
#ifdef BLUEPRINT_INCLUDE_TESTS
#include "tests/blueprint_EcmascriptEngineTests.cpp"
#endif
|
#ifndef _DIALOG_LAYER_H
#define _DIALOT_LAYER_H
#include "cocos2d.h"
class DialogLayer : public cocos2d::Layer
{
public:
virtual bool init();
void menuCloseCallback(cocos2d::Ref* pSender);
CREATE_FUNC(DialogLayer);
//virtual bool onTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent);
//virtual void onTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent);
//virtual void onTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent);
//void onEnter();
cocos2d::Menu *menu;
//void registerWithTouchDispatcher();
};
#endif
|
/***************************************************
* Mir Ali Talpur
* Matrix4.cpp
* 4/1/2015
***************************************************/
#include <math.h>
#include <iostream>
#include <iomanip>
#include <cstring>
#include "Matrix4.h"
#include "Vector4.h"
#include "Vector3.h"
#include <vector>
/***************************************************
* Matrix4()
* Constructor for the Matrix4 class
***************************************************/
Matrix4::Matrix4()
{
std::memset(m, 0, sizeof(m));
}
/***************************************************
* Matrix4(34 floats)
* Constructor for the Matrix class with 34 values
***************************************************/
Matrix4::Matrix4(
float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33 )
{
this->set(m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23,
m30, m31, m32, m33);
}
/***************************************************
* Set(34 floats)
* Sets all the matrix4 values correspondingly
***************************************************/
void Matrix4::set(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33)
{
m[0][0] = m00;
m[0][1] = m01;
m[0][2] = m02;
m[0][3] = m03;
m[1][0] = m10;
m[1][1] = m11;
m[1][2] = m12;
m[1][3] = m13;
m[2][0] = m20;
m[2][1] = m21;
m[2][2] = m22;
m[2][3] = m23;
m[3][0] = m30;
m[3][1] = m31;
m[3][2] = m32;
m[3][3] = m33;
}
/***************************************************
* get(int , element)
* Receive the value asked for in the matrix4
***************************************************/
float Matrix4::get(int vector,int element)
{
return m[vector][element];
}
/***************************************************
* Operator =
* Copis all the values of MAtrix4 to other_matrix4
***************************************************/
Matrix4& Matrix4::operator=(Matrix4 a)
{
std::memcpy(m, a.m, sizeof(m));
return *this;
}
/***************************************************
* prt()
* Returns the addres location of the Matrix4
***************************************************/
float* Matrix4::ptr()
{
return &m[0][0];
}
/***************************************************
* identity()
* Sets the Matrix4 as the Identity Matrix
***************************************************/
void Matrix4::identity()
{
static const float ident[4][4]={{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}};
std::memcpy(m, ident, sizeof(m));
}
/***************************************************
* multiply(Matrix4)
* multiply the matrix4 with another matrix4
***************************************************/
Matrix4 Matrix4::multiply(Matrix4 a)
{
Matrix4 b;
/********************************************************************
*essentially go thru the matrix size and keep a count of the values
*being added together. And in the inner most loop take the element
*in the first row multiple it by the first element in the column.
*Keep a count of those values and do it with the second element
*and add both the counts together and just keep doing that for the
*size of the matrix.
********************************************************************/
for (int row = 0; row < MAX_SIZE; row++) {
for (int col = 0; col < MAX_SIZE; col++) {
double count = 0;
for (int inner = 0; inner < MAX_SIZE; inner++){
count += m[row][inner] * a.m[inner][col];
}
b.m[row][col] = count;
}
}
return b;
}
/***************************************************
* Operator * Overload for matrix multipication
* multiply two matrices together
***************************************************/
Matrix4 Matrix4::operator * (Matrix4 a)
{
return multiply(a);
}
/***************************************************
* multiply(Vectror4)
* Multiply matrix4 by a Vector4
***************************************************/
Vector4 Matrix4::multiply(Vector4 a)
{
Vector4 b;
for(int i = 0; i < MAX_SIZE; i++){
for(int j = 0; j < MAX_SIZE; j++){
b.m[i] += m[i][j] * a.m[j];
}
}
return b;
}
/***************************************************
* Operator * Overload for matrix multipication
* multiply matrices by a Vector4
***************************************************/
Vector4 Matrix4::operator * (Vector4 a)
{
return multiply(a);
}
/***************************************************
* Multiply(Vector3)
* multiply matrices with a Vectro3
***************************************************/
Vector3 Matrix4::multiply(Vector3 a)
{
Vector3 b;
for(int i = 0; i < MAX_SIZE - 1; i++){
for(int j = 0; j < MAX_SIZE - 1; j++){
b.m[i] += m[i][j] * a.m[j];
}
}
return b;
}
/***************************************************
* Operator Overload *
* multiply matrices with a Vectro3
***************************************************/
Vector3 Matrix4::operator * (Vector3 a)
{
return multiply(a);
}
/***************************************************
* makeRotateX(float)
* rotate the cube about the X axis
***************************************************/
Matrix4 Matrix4::makeRotateX(float angle)
{
identity();
m[1][1] = cos(angle);
m[1][2] = -sin(angle);
m[2][1] = sin(angle);
m[2][2] = cos(angle);
return *this;
}
/***************************************************
* makeRotateY(float)
* rotate the cube about the Y axis
***************************************************/
Matrix4 Matrix4::makeRotateY(float angle)
{
identity();
m[0][0] = cos(angle);
m[0][2] = sin(angle);
m[2][0] = -sin(angle);
m[2][2] = cos(angle);
return *this;
}
/***************************************************
* makeRotateZ(float)
* rotate the cube about the Z axis
***************************************************/
Matrix4 Matrix4::makeRotateZ(float angle)
{
identity();
m[0][0] = cos(angle);
m[0][1] = -sin(angle);
m[1][0] = sin(angle);
m[1][1] = cos(angle);
return *this;
}
/***************************************************
* makeRotateArbitary(float)
* rotate the cube an arbitrary axis
***************************************************/
Matrix4 Matrix4::makeRotateArbitrary(Vector3 a, float angle)
{
identity();
m[0][0] = 1 + (1 - cos(angle)) * (pow(a.m[0], 2) - 1);
m[0][1] = -a.m[2] * sin(angle) + (1 - cos(angle)) * a.m[0] * a.m[1];
m[0][2] = a.m[1] * sin(angle) + (1 - cos(angle)) * a.m[0] * a.m[2];
m[1][0] = a.m[2] * sin(angle) + (1 - cos(angle)) * a.m[1] * a.m[0];
m[1][1] = 1 + (1 - cos(angle)) * (pow(a.m[1], 2) - 1);
m[1][2] = -a.m[0] * sin(angle) + (1 - cos(angle)) * a.m[1] * a.m[2];
m[2][0] = -a.m[1] * sin(angle) + (1 - cos(angle)) * a.m[2] * a.m[0];
m[2][1] = a.m[0] * sin(angle) + (1 - cos(angle)) * a.m[2] * a.m[1];
m[2][2] = 1 + (1 - cos(angle)) * (pow(a.m[2], 2) - 1);
return *this;
}
/***************************************************
* makeScale(float)
* scale the cube with the given values
***************************************************/
Matrix4 Matrix4::makeScale(float s)
{
return makeScale(s, s, s);
}
/***************************************************
* makeScale(float,float,float)
* scale the cube with the given values
***************************************************/
Matrix4 Matrix4::makeScale(float sx, float sy, float sz)
{
identity();
m[0][0] = sx;
m[1][1] = sy;
m[2][2] = sz;
return *this;
}
/***************************************************
* makeTranslate(float,float,float)
* translate the cube with the given values
***************************************************/
Matrix4 Matrix4::makeTranslate(float x, float y, float z)
{
identity();
m[0][3] = x;
m[1][3] = y;
m[2][3] = z;
return *this;
}
/***************************************************
* makeTranslate(Vector3)
* translate the cube with the given values
***************************************************/
Matrix4 Matrix4::makeTranslate(Vector3 a)
{
return makeTranslate(a[0], a[1], a[2]);
}
/***************************************************
* transpose(void)
* transpose the matrix basically the row and colmn
* interchange
***************************************************/
Matrix4 Matrix4::transpose(void)
{
Matrix4 b;
for(int x = 0; x < 4; ++x)
{
for(int y = 0; y < 4; ++y)
{
b.m[y][x] = m[x][y];
}
}
return b;
}
/***************************************************
* inverse(void)
* find the inverse of the 4 by 4 matrix
***************************************************/
Matrix4 Matrix4::inverse(void)
{
Matrix4 b;
/*
//start by searching for the maximum element
//in the matrix
//we also want to find the max row so we can
//swap afterwards
for(int i = 0; i < MAX_SIZE; i++){
double maxElement = abs(m[i][i]);
int maxRow = i;
for(int j = i; j < MAX_SIZE; j++){
if(abs(m[j][i]) > maxElement){
maxElement = abs(m[j][i]);
maxRow = j;
}
}
//swap max row with the current row
for(int j = i; j < MAX_SIZE + 1; j++){
double tmp = m[maxRow][j];
m[maxRow][j] = m[i][j];
m[i][j] = tmp;
}
//make the rows below 0 in the columns
for(int j = i + 1; j < MAX_SIZE; j++){
double count = -m[j][i] / m[i][i];
for(int k = i; j < MAX_SIZE + 1; j++){
if(i == k){
m[j][k] = 0;
}else{
m[j][k] += count * m[i][k];
}
}
}
}
//Ax = b
/*
Vector<double> x(n);
for(int i = MAX_SIZE - 1; i >= 0; i--){
x.m[i] = m[i][MAX_SIZE] / m[i][i];
for(int j = i; j >= 0; j--){
m[j][MAX_SIZE] -= m[j][i] * m[i];
}
}*/
int inner = 0 , count = 0;
float inv[16] = {}, holder[16] = {}, det;
//loop to put everything into the inv array
for(int i = 0; i < MAX_SIZE; i++){
for(int j = 0; j < MAX_SIZE; j++, inner++){
holder[inner] = m[i][j];
}
}
//multiply and set the values accordingly
inv[0] = holder[5] * holder[10] * holder[15] -
holder[5] * holder[11] * holder[14] -
holder[9] * holder[6] * holder[15] +
holder[9] * holder[7] * holder[14] +
holder[13] * holder[6] * holder[11] -
holder[13] * holder[7] * holder[10];
inv[4] = -holder[4] * holder[10] * holder[15] +
holder[4] * holder[11] * holder[14] +
holder[8] * holder[6] * holder[15] -
holder[8] * holder[7] * holder[14] -
holder[12] * holder[6] * holder[11] +
holder[12] * holder[7] * holder[10];
inv[8] = holder[4] * holder[9] * holder[15] -
holder[4] * holder[11] * holder[13] -
holder[8] * holder[5] * holder[15] +
holder[8] * holder[7] * holder[13] +
holder[12] * holder[5] * holder[11] -
holder[12] * holder[7] * holder[9];
inv[12] = -holder[4] * holder[9] * holder[14] +
holder[4] * holder[10] * holder[13] +
holder[8] * holder[5] * holder[14] -
holder[8] * holder[6] * holder[13] -
holder[12] * holder[5] * holder[10] +
holder[12] * holder[6] * holder[9];
inv[1] = -holder[1] * holder[10] * holder[15] +
holder[1] * holder[11] * holder[14] +
holder[9] * holder[2] * holder[15] -
holder[9] * holder[3] * holder[14] -
holder[13] * holder[2] * holder[11] +
holder[13] * holder[3] * holder[10];
inv[5] = holder[0] * holder[10] * holder[15] -
holder[0] * holder[11] * holder[14] -
holder[8] * holder[2] * holder[15] +
holder[8] * holder[3] * holder[14] +
holder[12] * holder[2] * holder[11] -
holder[12] * holder[3] * holder[10];
inv[9] = -holder[0] * holder[9] * holder[15] +
holder[0] * holder[11] * holder[13] +
holder[8] * holder[1] * holder[15] -
holder[8] * holder[3] * holder[13] -
holder[12] * holder[1] * holder[11] +
holder[12] * holder[3] * holder[9];
inv[13] = holder[0] * holder[9] * holder[14] -
holder[0] * holder[10] * holder[13] -
holder[8] * holder[1] * holder[14] +
holder[8] * holder[2] * holder[13] +
holder[12] * holder[1] * holder[10] -
holder[12] * holder[2] * holder[9];
inv[2] = holder[1] * holder[6] * holder[15] -
holder[1] * holder[7] * holder[14] -
holder[5] * holder[2] * holder[15] +
holder[5] * holder[3] * holder[14] +
holder[13] * holder[2] * holder[7] -
holder[13] * holder[3] * holder[6];
inv[6] = -holder[0] * holder[6] * holder[15] +
holder[0] * holder[7] * holder[14] +
holder[4] * holder[2] * holder[15] -
holder[4] * holder[3] * holder[14] -
holder[12] * holder[2] * holder[7] +
holder[12] * holder[3] * holder[6];
inv[10] = holder[0] * holder[7] * holder[13] -
holder[4] * holder[1] * holder[15] +
holder[4] * holder[3] * holder[13] +
holder[0] * holder[5] * holder[15] -
holder[12] * holder[1] * holder[7] -
holder[12] * holder[3] * holder[5];
inv[14] = -holder[0] * holder[5] * holder[14] +
holder[0] * holder[6] * holder[13] +
holder[4] * holder[1] * holder[14] -
holder[4] * holder[2] * holder[13] -
holder[12] * holder[1] * holder[6] +
holder[12] * holder[2] * holder[5];
inv[3] = -holder[1] * holder[6] * holder[11] +
holder[1] * holder[7] * holder[10] +
holder[5] * holder[2] * holder[11] -
holder[5] * holder[3] * holder[10] -
holder[9] * holder[2] * holder[7] +
holder[9] * holder[3] * holder[6];
inv[7] = holder[0] * holder[6] * holder[11] -
holder[0] * holder[7] * holder[10] -
holder[4] * holder[2] * holder[11] +
holder[4] * holder[3] * holder[10] +
holder[8] * holder[2] * holder[7] -
holder[8] * holder[3] * holder[6];
inv[11] = -holder[0] * holder[5] * holder[11] +
holder[0] * holder[7] * holder[9] +
holder[4] * holder[1] * holder[11] -
holder[4] * holder[3] * holder[9] -
holder[8] * holder[1] * holder[7] +
holder[8] * holder[3] * holder[5];
inv[15] = holder[0] * holder[5] * holder[10] -
holder[0] * holder[6] * holder[9] -
holder[4] * holder[1] * holder[10] +
holder[4] * holder[2] * holder[9] +
holder[8] * holder[1] * holder[6] -
holder[8] * holder[2] * holder[5];
det = holder[0] * inv[0] + holder[1] * inv[4] + holder[2] * inv[8] + holder[3] * inv[12];
det = 1.0 / det;
for(int i = 0; i < MAX_SIZE; i++){
for(int j = 0; j < MAX_SIZE; j++, count++){
b.m[i][j] = inv[count] * det;
}
}
return b;
}
Matrix4 Matrix4::orthoNormalInverse(void)
{
Matrix4 b;
//Calculate the inverse of this matrix with the assumption that it is ortho-normal
//This will be useful when implementing cameras!
return b;
}
void Matrix4::print(std::string comment)
{
//Width constants and variables
static const int pointWidth = 1;
static const int precisionWidth = 4;
int integerWidth = 1;
//Determine the necessary width to the left of the decimal point
float* elementPtr = (float*)m;
float maxValue = fabsf(*(elementPtr++));
while(elementPtr++ < ((float*)m+16)) if(fabsf(*elementPtr) > maxValue) maxValue = fabsf(*elementPtr);
while(maxValue >= 10.0) { ++integerWidth; maxValue /= 10.0; }
//Sum up the widths to determine the cell width needed
int cellWidth = integerWidth + pointWidth + precisionWidth;
//Set the stream parameters for fixed number of digits after the decimal point
//and a set number of precision digits
std::cout << std::fixed;
std::cout << std::setprecision(precisionWidth);
//Print the comment
std::cout << comment << std::endl;
//Loop through the matrix elements, format each, and print them to screen
float cellValue;
for(int element = 0; element < 4; element++)
{
std::cout << std::setw(1) << (element == 0 ? "[" : " ");
for(int vector = 0; vector < 4; vector++)
{
cellValue = m[vector][element];
std::cout << std::setw(cellWidth + (cellValue >= 0.0 ? 1 : 0)) << cellValue;
std::cout << std::setw(0) << (vector < 3 ? " " : "");
}
std::cout << std::setw(1) << (element == 3 ? "]" : " ") << std::endl;
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define debug(x) cout << '>' << #x << ':' << x << endl;
#define all(v) v.begin(), v.end()
#define pii pair<int, int>
#define mxN 1e7
#define newl cout << "\n"
#define vi vector<int>
typedef pair<int, pair<int, int>> threepair;
class Solution {
public:
int largestRectangleArea(vector<int>& arr) {
int ans = 0;
stack<int> st;
arr.push_back(-2342);
int n = arr.size();
st.push(0);
for(int i = 1; i < n; i++) {
// condition will result in 'strictly' increasing order of array
while(!st.empty() && arr[st.top()] >= arr[i]) {
auto top = st.top(); st.pop();
// popped element will be sandwiched between lower height due to strict increasing nature
int h = arr[top];
// left border's height will be less than h's height, due to strictly increasing property
int left = st.empty() ? -1 : st.top();
// right border's height will be less than h's height, due to while loop entry(i.e enter while loop if curr element is smaller or equal to top of stack(remember stack maintains strictly increasing order)) condition. (this is why dummy node at last is required)
int right = i;
ans = max(ans, h*(right-left-1));
}
st.push(i);
}
return ans;
}
};
/* This is same concept used in stack. take ith element, find its left border(closest element towards left which is just less than ith height), find right border(closest element in right which is just less than ith height)
int largestRectangleArea(vector<int>& arr) {
int ans = 0, n = arr.size();
if(n == 0) return 0;
vector<int> lessleft(n, 0), lessright(n, 0);
lessleft[0] = -1;
lessright[n-1] = n;
for(int i = 1; i < n; i++) {
int idx = i-1;
while(idx >= 0 && arr[idx] >= arr[i]) idx = lessleft[idx];
lessleft[i] = idx;
}
for(int i = n-2; i >= 0; i--) {
int idx = i+1;
while(idx < n && arr[idx] >= arr[i]) idx = lessright[idx];
lessright[i] = idx;
}
for(int i = 0; i < n; i++) {
int left = lessleft[i];
int right = lessright[i];
int h = arr[i];
ans = max(ans, h*(right-left-1));
}
return ans;
}
*/
int main() {
auto sol = Solution();
vector<vector<int>> arr = {{1, 2}, {1, 3}, {2, 3}};
vector<int> vec = {2, 3, 4};
int n = arr.size();
// auto res = sol.largestRectangleArea(vec, );
// debug(res.size());
vector<int> v;
}
|
#include "basepawn.hh"
#include <QPointF>
#include <QPolygonF>
#include <QVector>
#include <QBrush>
basepawn::basepawn(int id) {
playerId = id;
QVector<QPointF> basePoints;
basePoints << QPointF(0, 0) << QPointF(1, 0) << QPointF(0, 1)
<< QPointF(1, 1) << QPointF(0, 0);
int scaler = 7;
for (int i = 0; i < basePoints.size(); ++i) {
basePoints[i] *= scaler;
}
QPolygonF boxPawn(basePoints);
setPolygon(boxPawn);
}
void basepawn::colorPawn() {
QBrush brush;
brush.setStyle(Qt::SolidPattern);
if (playerId == 1) {
brush.setColor(Qt::red);
} else {
brush.setColor(Qt::black);
}
setBrush(brush);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 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/display/vis_dev.h"
#include "modules/widgets/WidgetContainer.h"
#include "modules/widgets/OpButton.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/pi/OpView.h"
#include "modules/inputmanager/inputaction.h"
#include "modules/inputmanager/inputmanager.h"
#include "modules/prefs/prefsmanager/collections/pc_display.h"
#include "modules/util/hash.h"
#include "modules/doc/frm_doc.h"
#ifdef QUICK
# include "adjunct/quick/Application.h"
# include "adjunct/quick_toolkit/widgets/OpWorkspace.h"
# include "adjunct/quick/windows/DocumentDesktopWindow.h"
#endif
#ifdef DRAG_SUPPORT
#include "modules/dragdrop/dragdrop_manager.h"
#include "modules/pi/OpDragObject.h"
#endif // DRAG_SUPPORT
#ifdef NAMED_WIDGET
// == OpNamedWidgetsCollection ========================================
OpNamedWidgetsCollection::OpNamedWidgetsCollection()
{
m_named_widgets.SetHashFunctions(&m_hash_function);
}
OpNamedWidgetsCollection::~OpNamedWidgetsCollection()
{
OP_ASSERT(m_named_widgets.GetCount() == 0);
}
#endif // NAMED_WIDGET
// == RootWidget ========================================
class RootWidget : public OpWidget
#ifdef NAMED_WIDGET
, public OpNamedWidgetsCollection
#endif // NAMED_WIDGET
{
public:
RootWidget(WidgetContainer* container)
{
SetWidgetContainer(container);
#ifdef QUICK
SetSkinned(TRUE);
#endif
#ifdef SKIN_SUPPORT
SetSkinIsBackground(TRUE);
#endif // SKIN_SUPPORT
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
AccessibilitySkipsMe(TRUE);
#endif
}
void OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect)
{
if (GetWidgetContainer()->GetEraseBg())
{
if (!m_color.use_default_background_color)
{
vis_dev->SetColor32(m_color.background_color);
vis_dev->FillRect(paint_rect);
}
}
}
void OnMouseUp(const OpPoint &point, MouseButton button, UINT8 nclicks)
{
if (listener && button == MOUSE_BUTTON_1 && GetBounds().Contains(point))
listener->OnClick(this, GetID());
}
void OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks)
{
if (listener && GetBounds().Contains(point))
listener->OnMouseEvent(this, 0, point.x, point.y, button, TRUE, nclicks);
}
#ifdef NAMED_WIDGET
OpNamedWidgetsCollection *GetNamedWidgetsCollection()
{
return this;
}
#endif // NAMED_WIDGET
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
Type GetType() {return WIDGET_TYPE_ROOT;}
#endif
};
#ifdef WIDGETS_IME_SUPPORT
// == WidgetInputMethodListener ========================================
WidgetInputMethodListener::WidgetInputMethodListener()
: inputcontext(NULL)
{
}
IM_WIDGETINFO WidgetInputMethodListener::OnStartComposing(OpInputMethodString* imstring, IM_COMPOSE compose)
{
IM_WIDGETINFO widgetinfo;
widgetinfo.rect.Set(0, 0, 0, 0);
widgetinfo.font = NULL;
widgetinfo.is_multiline = FALSE;
OP_ASSERT(inputcontext == NULL);
inputcontext = g_input_manager->GetKeyboardInputContext();
if (inputcontext)
{
widgetinfo = inputcontext->OnStartComposing(imstring, compose);
}
return widgetinfo;
}
IM_WIDGETINFO WidgetInputMethodListener::OnCompose()
{
IM_WIDGETINFO widgetinfo;
widgetinfo.rect.Set(0, 0, 0, 0);
widgetinfo.font = NULL;
widgetinfo.is_multiline = FALSE;
OP_ASSERT(inputcontext);
if (inputcontext)
{
widgetinfo = inputcontext->OnCompose();
}
return widgetinfo;
}
void WidgetInputMethodListener::OnCommitResult()
{
OP_ASSERT(inputcontext);
if (inputcontext)
inputcontext->OnCommitResult();
}
void WidgetInputMethodListener::OnStopComposing(BOOL canceled)
{
OP_ASSERT(inputcontext);
if (inputcontext)
inputcontext->OnStopComposing(canceled);
inputcontext = NULL;
}
#ifdef IME_RECONVERT_SUPPORT
void WidgetInputMethodListener::OnPrepareReconvert(const uni_char*& str, int& sel_start, int& sel_stop)
{
if (inputcontext)
inputcontext->OnPrepareReconvert(str,sel_start,sel_stop);
}
void WidgetInputMethodListener::OnReconvertRange(int sel_start, int sel_stop)
{
OP_ASSERT(inputcontext);
if (inputcontext)
inputcontext->OnReconvertRange(sel_start,sel_stop);
}
#endif // IME_RECONVERT_SUPPORT
void WidgetInputMethodListener::OnCandidateShow(BOOL visible)
{
OP_ASSERT(inputcontext);
if (inputcontext)
inputcontext->OnCandidateShow(visible);
}
IM_WIDGETINFO WidgetInputMethodListener::GetWidgetInfo()
{
IM_WIDGETINFO widgetinfo;
widgetinfo.rect.Set(0, 0, 0, 0);
widgetinfo.font = NULL;
widgetinfo.is_multiline = FALSE;
OP_ASSERT(inputcontext);
if (inputcontext)
{
widgetinfo = inputcontext->GetWidgetInfo();
}
return widgetinfo;
}
#endif // WIDGETS_IME_SUPPORT
#ifndef MOUSELESS
// == ContainerMouseListener ========================================
class ContainerMouseListener : public CoreViewMouseListener
{
public:
ContainerMouseListener(WidgetContainer* widgetcontainer)
: last_nclicks(1)
, widgetcontainer(widgetcontainer)
#ifdef QUICK
, m_button_down(false)
#endif //QUICK
{
}
CoreView* GetMouseHitView(const OpPoint &point, CoreView* view)
{
return view->GetIntersectingChild(point.x, point.y);
}
OpPoint GetMousePos(const OpPoint& point)
{
INT32 xpos = widgetcontainer->GetRoot()->GetVisualDevice()->ScaleToDoc(point.x);
INT32 ypos = widgetcontainer->GetRoot()->GetVisualDevice()->ScaleToDoc(point.y);
return OpPoint(xpos, ypos);
}
void OnMouseMove(const OpPoint &point, ShiftKeyState keystate, CoreView* view)
{
#ifdef PAN_SUPPORT
OP_ASSERT(widgetcontainer->GetVisualDevice());
OpWidget* widget = widgetcontainer->GetRoot();
while (widget && !widget->IsScrollable(FALSE) && !widget->IsScrollable(TRUE))
widget = widgetcontainer->GetNextFocusableWidget(widget, TRUE);
// fallback to root widget
if (!widget)
widget = widgetcontainer->GetRoot();
if (widget && widgetcontainer->GetVisualDevice()->PanMouseMove(view->ConvertToScreen(point), widget))
return;
#endif // PAN_SUPPORT
WidgetSafePointer captured_widget(g_widget_globals->captured_widget);
widgetcontainer->GetRoot()->GenerateOnMouseMove(GetMousePos(point));
// The widget may have been deleted at this point (on Mac).
if (captured_widget.IsDeleted())
return;
widgetcontainer->GetRoot()->GenerateOnSetCursor(GetMousePos(point));
#ifdef QUICK
if (!m_button_down)
{
OpWidget* inner_widget = widgetcontainer->GetRoot()->GetWidget(GetMousePos(point), TRUE);
if (g_application && inner_widget)
g_application->SetToolTipListener(inner_widget);
}
#endif // QUICK
}
void OnMouseLeave()
{
#ifdef QUICK
widgetcontainer->GetRoot()->GenerateOnMouseLeave();
g_application->SetToolTipListener(NULL);
#endif // QUICK
}
void OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks, ShiftKeyState keystate, CoreView* view)
{
#ifdef QUICK
m_button_down = true;
#endif // QUICK
last_nclicks = nclicks;
#ifdef PAN_SUPPORT
OP_ASSERT(widgetcontainer->GetVisualDevice());
if (button == MOUSE_BUTTON_1)
widgetcontainer->GetVisualDevice()->PanMouseDown(view->ConvertToScreen(point), keystate);
#endif // PAN_SUPPORT
widgetcontainer->GetRoot()->GenerateOnMouseDown(GetMousePos(point), button, nclicks);
}
void OnMouseUp(const OpPoint &point, MouseButton button, ShiftKeyState keystate, CoreView* view)
{
#ifdef QUICK
m_button_down = false;
g_application->SetToolTipListener(NULL);
#endif // QUICK
#ifdef PAN_SUPPORT
OP_ASSERT(widgetcontainer->GetVisualDevice());
if (button == MOUSE_BUTTON_1 && widgetcontainer->GetVisualDevice()->PanMouseUp())
return;
#endif // PAN_SUPPORT
widgetcontainer->GetRoot()->GenerateOnMouseUp(GetMousePos(point), button, last_nclicks);
}
BOOL OnMouseWheel(INT32 delta,BOOL vertical, ShiftKeyState keystate, CoreView* view)
{
BOOL handled = FALSE;
if (g_widget_globals->hover_widget)
{
handled = g_widget_globals->hover_widget->GenerateOnMouseWheel(delta,vertical);
}
if (handled == FALSE && OpWidget::GetFocused())
{
handled = OpWidget::GetFocused()->GenerateOnMouseWheel(delta,vertical);
}
return handled;
}
void OnSetCursor() {}
private:
UINT8 last_nclicks;
WidgetContainer* widgetcontainer;
#ifdef QUICK
bool m_button_down;
#endif //QUICK
};
#endif // !MOUSELESS
// == ContainerPaintListener ========================================
class ContainerPaintListener : public CoreViewPaintListener
{
private:
ContainerPaintListener(WidgetContainer* widgetcontainer)
: widgetcontainer(widgetcontainer)
, vd(NULL)
{}
public:
static ContainerPaintListener* Create(WidgetContainer* widgetcontainer)
{
ContainerPaintListener* cpl = OP_NEW(ContainerPaintListener, (widgetcontainer));
if (cpl == NULL)
return NULL;
// Initialise the visual device
cpl->vd = OP_NEW(VisualDevice, ());
if (cpl->vd)
{
cpl->vd->SetView(widgetcontainer->GetView());
return cpl;
}
else
{
OP_DELETE(cpl);
return NULL;
}
}
~ContainerPaintListener()
{
if (vd)
{
vd->painter = NULL;
vd->SetView(NULL);
}
OP_DELETE(vd);
}
BOOL BeforePaint()
{
widgetcontainer->GetRoot()->GenerateOnBeforePaint();
# ifdef QUICK // SyncLayout isn't a method of OpWidget otherwise ...
widgetcontainer->GetRoot()->SyncLayout();
# endif // QUICK
return TRUE;
}
void OnPaint(const OpRect &crect, OpPainter* painter, CoreView* view, int translate_x, int translate_y)
{
OpRect doc_rect = vd->ScaleToDoc(crect);
OpRect view_rect;
view->GetSize(&view_rect.width, &view_rect.height);
AffinePos view_ctm;
view->GetTransformToContainer(view_ctm);
view_ctm.AppendTranslation(translate_x, translate_y);
vd->BeginPaint(painter, view_rect, doc_rect, view_ctm);
widgetcontainer->GetRoot()->GenerateOnPaint(doc_rect);
vd->EndPaint();
}
public:
WidgetContainer* widgetcontainer;
VisualDevice* vd;
};
#ifdef TOUCH_EVENTS_SUPPORT
class ContainerTouchListener : public CoreViewTouchListener
{
public:
ContainerTouchListener(WidgetContainer* widgetcontainer, ContainerMouseListener* mouselistener)
: m_widgetcontainer(widgetcontainer)
, m_mouselistener(mouselistener)
, m_scroll_widget(NULL)
{
}
CoreView* GetTouchHitView(const OpPoint &point, CoreView* view)
{
return m_mouselistener->GetMouseHitView(point, view);
}
OpPoint GetTouchPos(const OpPoint& point)
{
return m_mouselistener->GetMousePos(point);
}
virtual void OnTouchDown(int id, const OpPoint &point, int radius, ShiftKeyState modifiers, CoreView* view, void* user_data)
{
m_start_point = point;
m_last_move_point = point;
// for compatibility, send a mouse down now
view->MouseDown(point, MOUSE_BUTTON_1, 1, modifiers);
// simulate the button being down
view->SetMouseButton(MOUSE_BUTTON_1, true);
// with touch move, we only do something for scrollable widgets
m_scroll_widget = g_widget_globals->captured_widget;
if (m_scroll_widget)
{
if(!m_scroll_widget->IsScrollable(FALSE) && !m_scroll_widget->IsScrollable(TRUE))
{
m_scroll_widget = NULL;
}
}
}
virtual void OnTouchUp(int id, const OpPoint &point, int radius, ShiftKeyState modifiers, CoreView* view, void* user_data)
{
// for compatibility, send a mouse up now
if(FramesDocument::CheckMovedTooMuchForClick(point, m_start_point))
{
view->MouseUp(point, MOUSE_BUTTON_1, modifiers);
}
else
{
// we have moved too much from the initial position to consider this a "click".
view->MouseLeave();
}
view->SetMouseButton(MOUSE_BUTTON_1, false);
m_scroll_widget = NULL;
}
virtual void OnTouchMove(int id, const OpPoint &point, int radius, ShiftKeyState modifiers, CoreView* view, void* user_data)
{
BOOL scrolled = FALSE;
if (m_scroll_widget)
{
INT32 delta_x = m_last_move_point.x - point.x;
INT32 delta_y = m_last_move_point.y - point.y;
if (delta_y)
scrolled |= m_scroll_widget->GenerateOnScrollAction(delta_y, TRUE);
if (delta_x)
scrolled |= m_scroll_widget->GenerateOnScrollAction(delta_x, FALSE);
m_widgetcontainer->GetRoot()->GenerateOnSetCursor(GetTouchPos(point));
m_last_move_point = point;
}
if(!scrolled && !m_scroll_widget)
{
// for compatibility, send a mouse move now if we didn't scroll
view->MouseMove(point, modifiers);
}
}
private:
OpPoint m_last_move_point; // last point of the move
OpPoint m_start_point; // the touch down initial point
WidgetContainer* m_widgetcontainer;
ContainerMouseListener* m_mouselistener;
OpWidget* m_scroll_widget;
};
#endif // TOUCH_EVENTS_SUPPORT
// == WidgetContainer ========================================
WidgetContainer::WidgetContainer(DesktopWindow* parent_desktop_window) :
root(NULL)
, view(NULL)
, erase_bg(FALSE)
, is_focusable(FALSE)
, m_parent_desktop_window(parent_desktop_window)
, paint_listener(NULL)
, mouse_listener(NULL)
#ifdef TOUCH_EVENTS_SUPPORT
, touch_listener(NULL)
#endif // TOUCH_EVENTS_SUPPORT
, m_has_default_button(TRUE)
{
}
OP_STATUS WidgetContainer::Init(const OpRect &rect, OpWindow* window, CoreView* parentview)
{
this->window = window;
if (parentview)
RETURN_IF_ERROR(CoreView::Create(&view, parentview));
else
RETURN_IF_ERROR(CoreViewContainer::Create(&view, window, NULL, NULL));
AffinePos pos(rect.x, rect.y);
view->SetPos(pos);
view->SetSize(rect.width, rect.height);
view->SetVisibility(TRUE);
paint_listener = ContainerPaintListener::Create(this);
#ifndef MOUSELESS
mouse_listener = OP_NEW(ContainerMouseListener, (this));
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
touch_listener = OP_NEW(ContainerTouchListener, (this, mouse_listener));
#endif // TOUCH_EVENTS_SUPPORT
if (paint_listener == NULL
#ifndef MOUSELESS
|| mouse_listener == NULL
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
|| touch_listener == NULL
#endif // TOUCH_EVENTS_SUPPORT
|| paint_listener->vd == NULL)
{
OP_DELETE(paint_listener);
paint_listener = NULL;
#ifdef TOUCH_EVENTS_SUPPORT
OP_DELETE(touch_listener);
touch_listener = NULL;
#endif // TOUCH_EVENTS_SUPPORT
#ifndef MOUSELESS
OP_DELETE(mouse_listener);
mouse_listener = NULL;
#endif // !MOUSELESS
return OpStatus::ERR_NO_MEMORY;
}
view->SetParentInputContext(this);
#ifdef WIDGETS_IME_SUPPORT
view->GetOpView()->SetInputMethodListener(g_im_listener);
#endif
view->SetPaintListener(paint_listener);
#ifndef MOUSELESS
view->SetMouseListener(mouse_listener);
#endif // !MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
view->SetTouchListener(touch_listener);
#endif // TOUCH_EVENTS_SUPPORT
#ifdef DRAG_SUPPORT
view->SetDragListener(this);
#endif
// Init the root widget
root = OP_NEW(RootWidget, (this));
if (root == NULL)
{
OP_DELETE(paint_listener);
paint_listener = NULL;
#ifdef TOUCH_EVENTS_SUPPORT
OP_DELETE(touch_listener);
touch_listener = NULL;
#endif // TOUCH_EVENTS_SUPPORT
#ifndef MOUSELESS
OP_DELETE(mouse_listener);
mouse_listener = NULL;
#endif // !MOUSELESS
return OpStatus::ERR_NO_MEMORY;
}
if (OpStatus::IsMemoryError(root->init_status))
{
OP_STATUS stat = root->init_status;
root->Delete();
root = NULL;
OP_DELETE(paint_listener);
paint_listener = NULL;
#ifdef TOUCH_EVENTS_SUPPORT
OP_DELETE(touch_listener);
touch_listener = NULL;
#endif // TOUCH_EVENTS_SUPPORT
#ifndef MOUSELESS
OP_DELETE(mouse_listener);
mouse_listener = NULL;
#endif // !MOUSELESS
return stat;
}
root->SetParentInputContext(this);
root->SetVisualDevice(paint_listener->vd);
root->SetRect(paint_listener->vd->ScaleToDoc(OpRect(0, 0, rect.width, rect.height)));
AffinePos doc_pos;
root->SetPosInDocument(doc_pos);
OP_STATUS status;
TRAP(status, g_pcdisplay->RegisterListenerL(this));
OpStatus::Ignore(status);
return OpStatus::OK;
}
WidgetContainer::~WidgetContainer()
{
g_pcdisplay->UnregisterListener(this);
if (root)
{
root->Delete();
}
if (view)
{
view->SetPaintListener(NULL);
#ifdef TOUCH_EVENTS_SUPPORT
view->SetTouchListener(NULL);
#endif // TOUCH_EVENTS_SUPPORT
#ifndef MOUSELESS
view->SetMouseListener(NULL);
#endif // !MOUSELESS
}
OP_DELETE(paint_listener);
#ifdef TOUCH_EVENTS_SUPPORT
OP_DELETE(touch_listener);
#endif // TOUCH_EVENTS_SUPPORT
#ifndef MOUSELESS
OP_DELETE(mouse_listener);
#endif // !MOUSELESS
OP_DELETE(view);
}
CoreView* WidgetContainer::GetView()
{
return view;
}
OpView* WidgetContainer::GetOpView()
{
return view->GetOpView();
}
void WidgetContainer::SetPos(const AffinePos& pos)
{
view->SetPos(pos);
}
void WidgetContainer::SetSize(INT32 width, INT32 height)
{
view->SetSize(width, height);
if (paint_listener && paint_listener->vd)
root->SetRect(paint_listener->vd->ScaleToDoc(OpRect(0, 0, width, height)));
}
VisualDevice* WidgetContainer::GetVisualDevice()
{
return paint_listener ? paint_listener->vd : NULL;
}
BOOL WidgetContainer::OnInputAction(OpInputAction* action)
{
#ifdef WIDGETS_UI
switch (action->GetAction())
{
#ifdef BUTTON_GROUP_SUPPORT
case OpInputAction::ACTION_FOCUS_NEXT_RADIO_WIDGET:
case OpInputAction::ACTION_FOCUS_PREVIOUS_RADIO_WIDGET:
{
OpWidget* widget = OpWidget::GetFocused();
if(widget && widget->GetType() == OpTypedObject::WIDGET_TYPE_RADIOBUTTON && static_cast<OpRadioButton*>(widget)->m_button_group)
{
widget = action->GetAction() == OpInputAction::ACTION_FOCUS_NEXT_RADIO_WIDGET ? widget->GetNextSibling() : widget->GetPreviousSibling();
while (widget && (widget->GetType() != OpTypedObject::WIDGET_TYPE_RADIOBUTTON || !widget->IsInputContextAvailable(FOCUS_REASON_OTHER)))
{
widget = action->GetAction() == OpInputAction::ACTION_FOCUS_NEXT_RADIO_WIDGET ? widget->GetNextSibling() : widget->GetPreviousSibling();
}
if (widget && (widget->GetType() == OpTypedObject::WIDGET_TYPE_RADIOBUTTON
#ifdef WIDGETS_TABS_AND_TOOLBAR_BUTTONS_ARE_TAB_STOP
|| (widget->GetType() == OpTypedObject::WIDGET_TYPE_BUTTON && (static_cast<OpButton*>(widget)->GetButtonType() == OpButton::TYPE_TAB || static_cast<OpButton*>(widget)->GetButtonType() == OpButton::TYPE_PAGEBAR))
#endif
))
{
GetRoot()->SetHasFocusRect(TRUE);
static_cast<OpRadioButton*>(widget)->SetValue(TRUE);
static_cast<OpRadioButton*>(widget)->SetFocus(FOCUS_REASON_KEYBOARD);
// invoke listener
if (widget->GetListener())
{
widget->GetListener()->OnClick(widget, widget->GetID()); // Invoke!
}
return TRUE;
}
}
return FALSE;
}
#endif // BUTTON_GROUP_SUPPORT
case OpInputAction::ACTION_FOCUS_NEXT_WIDGET:
case OpInputAction::ACTION_FOCUS_PREVIOUS_WIDGET:
{
BOOL forward = action->GetAction() == OpInputAction::ACTION_FOCUS_NEXT_WIDGET;
// Move focus
OpWidget* focus_widget = OpWidget::GetFocused();
if (!focus_widget)
{
// if we don't have a previous focus, try so check if current input context
// exist below us
OpInputContext* input_context = g_input_manager->GetKeyboardInputContext();
while (input_context && !focus_widget)
{
OpWidget* widget = GetRoot();
while (widget)
{
if (input_context == widget)
{
focus_widget = widget;
break;
}
if (widget->childs.First())
{
widget = (OpWidget*) widget->childs.First();
}
else
{
while (widget->Suc() == NULL && widget->parent)
{
widget = widget->parent;
}
widget = (OpWidget*) widget->Suc();
}
}
input_context = input_context->GetParentInputContext();
}
}
if (focus_widget)
{
focus_widget = GetNextFocusableWidget(focus_widget, forward);
}
#ifdef QUICK
if (GetParentDesktopWindow())
{
DocumentDesktopWindow* doc_parent = GetParentDesktopWindow()->GetType() == WINDOW_TYPE_DOCUMENT ?
static_cast<DocumentDesktopWindow*>(GetParentDesktopWindow()) :
NULL;
/* This speed dial check was introduced to fix DSK-331040.
In order to cycle back to the top when tabbing, we want the speed dial to get the
next focusable widget from the root, and not from the parent workspace,
so it works like it does with forms on web pages.*/
bool is_speed_dial = doc_parent && doc_parent->IsSpeedDialActive();
if (!focus_widget && !is_speed_dial && GetParentDesktopWindow()->GetParentWorkspace())
{
focus_widget = GetNextFocusableWidget(GetParentDesktopWindow()->GetParentWorkspace(), forward);
if (!focus_widget)
{
focus_widget = GetNextFocusableWidget(GetParentDesktopWindow()->GetParentWorkspace()->GetWidgetContainer()->GetRoot(), forward);
}
}
}
#endif
if (!focus_widget)
{
focus_widget = GetNextFocusableWidget(GetRoot(), forward);
}
if (focus_widget)
{
GetRoot()->SetHasFocusRect(TRUE);
focus_widget->SetFocus(FOCUS_REASON_KEYBOARD);
}
return TRUE;
}
case OpInputAction::ACTION_CLICK_DEFAULT_BUTTON:
{
// find default push button and click it
OpWidget* widget = GetRoot();
while (widget)
{
if (widget->GetType() == WIDGET_TYPE_BUTTON)
{
OpButton* button = (OpButton*) widget;
if (button->HasDefaultLook())
{
#ifdef QUICK
button->Click();
#endif
return TRUE;
}
}
if (widget->IsVisible() && widget->childs.First())
{
widget = (OpWidget*) widget->childs.First();
}
else
{
while (widget->Suc() == NULL && widget->parent)
{
widget = widget->parent;
}
widget = (OpWidget*) widget->Suc();
}
}
return FALSE;
}
default:
break;
}
#endif // WIDGETS_UI
return FALSE;
}
OpWidget* WidgetContainer::GetNextFocusableWidget(OpWidget* widget, BOOL forward)
{
#ifdef WIDGETS_UI
if (widget == NULL)
{
return NULL;
}
#ifdef BUTTON_GROUP_SUPPORT
OpWidget* old_parent = widget->parent;
#endif // BUTTON_GROUP_SUPPORT
OpRadioButton* fallback_radio_button = NULL;
BOOL next = FALSE;
do
{
if (forward)
{
if (widget->IsVisible() && widget->childs.First() && !fallback_radio_button)
{
widget = (OpWidget*) widget->childs.First();
}
else
{
if (fallback_radio_button && !widget->Suc())
{
widget = fallback_radio_button;
break;
}
while (widget->Suc() == NULL && widget->parent)
{
widget = widget->parent;
}
widget = (OpWidget*) widget->Suc();
}
}
else
{
if (widget == root)
{
while (widget->IsVisible() && widget->childs.Last())
{
widget = (OpWidget*) widget->childs.Last();
}
}
else if (widget->Pred())
{
widget = (OpWidget*) widget->Pred();
while (!fallback_radio_button && widget->IsVisible() && widget->childs.Last())
{
widget = (OpWidget*) widget->childs.Last();
}
}
else
{
if (fallback_radio_button)
{
widget = fallback_radio_button;
break;
}
widget = widget->parent;
}
}
next = FALSE;
#ifdef BUTTON_GROUP_SUPPORT
if(widget && ((widget->GetType() == OpTypedObject::WIDGET_TYPE_RADIOBUTTON && static_cast<OpRadioButton*>(widget)->m_button_group)
#ifdef WIDGETS_TABS_AND_TOOLBAR_BUTTONS_ARE_TAB_STOP
|| (widget->GetType() == OpTypedObject::WIDGET_TYPE_BUTTON && (((OpButton*)widget)->GetButtonType() == OpButton::TYPE_TAB || ((OpButton*)widget)->GetButtonType() == OpButton::TYPE_PAGEBAR))
#endif
))
{
next = old_parent == widget->parent;
if (!next)
{
next = ((OpRadioButton*)widget)->GetValue() == FALSE;
if (next && !fallback_radio_button && widget->IsEnabled() && widget->IsAllVisible() && widget->IsTabStop())
{
fallback_radio_button = (OpRadioButton*) widget;
}
}
}
else if (fallback_radio_button)
{
next = TRUE;
}
#endif // BUTTON_GROUP_SUPPORT
} while (widget && widget != root && (!widget->IsEnabled() || !widget->IsAllVisible() || !widget->IsTabStop() || next));
if (widget == root)
{
widget = NULL;
}
return widget;
#else // WIDGETS_UI
OP_ASSERT(NULL); // You need WIDGETS_UI
return NULL;
#endif
}
/***********************************************************************************
**
** UpdateDefaultPushButton
**
***********************************************************************************/
void WidgetContainer::UpdateDefaultPushButton()
{
#ifdef WIDGETS_UI
#ifdef SKIN_SUPPORT
if (m_has_default_button)
{
// if window is inactive, noone should have default look
// if window is active, a focused push button should have the look, otherwise
// the one with packed2.has_defaultlook should have it, as long as it isn't disabled
OpWidget* widget = GetRoot();
OpButton* focused_button = NULL;
if (g_input_manager->GetKeyboardInputContext() && g_input_manager->GetKeyboardInputContext()->GetType() == OpTypedObject::WIDGET_TYPE_BUTTON)
{
focused_button = (OpButton*) g_input_manager->GetKeyboardInputContext();
}
#ifdef _MACINTOSH_
// Note: MacOS never changes default button it's always the same!
// So if this function is attempting to change the default button using the
// currently focused button then just jump out!
if (focused_button != NULL)
{
WidgetContainer *wc = focused_button->GetWidgetContainer();
// The focused button that we have grabbed must be in the same widget container (i.e. Dialog)
// This was added since sometimes we have a dialog come over another dialog
if (wc != this)
focused_button = NULL;
else
return;
}
#endif
while (widget)
{
if (widget->GetType() == OpTypedObject::WIDGET_TYPE_BUTTON)
{
OpButton* button = (OpButton*) widget;
if (button->GetButtonType() == OpButton::TYPE_PUSH_DEFAULT || button->GetButtonType() == OpButton::TYPE_PUSH)
{
BOOL in_active_win = TRUE;
#ifdef QUICK
#ifndef _MACINTOSH_
DesktopWindow* parent_desktop = GetParentDesktopWindow();
in_active_win = parent_desktop && parent_desktop->IsActive();
#endif
#endif
if (in_active_win && ((!focused_button && button->HasDefaultLook() && button->IsEnabled()) || (focused_button == button)))
{
button->SetButtonTypeAndStyle(OpButton::TYPE_PUSH_DEFAULT, button->m_button_style, TRUE);
}
else
{
button->SetButtonTypeAndStyle(OpButton::TYPE_PUSH, button->m_button_style, TRUE);
}
}
}
if (widget->IsVisible() && widget->childs.First())
{
widget = (OpWidget*) widget->childs.First();
}
else
{
while (widget->Suc() == NULL && widget->parent)
{
widget = widget->parent;
}
widget = (OpWidget*) widget->Suc();
}
}
} // end if (m_has_default_button)
#endif // SKIN_SUPPORT
#endif // WIDGETS_UI
}
#ifdef DRAG_SUPPORT
void WidgetContainer::OnDragStart(CoreView* view, const OpPoint& start_point, ShiftKeyState modifiers, const OpPoint& current_point)
{
OpWidget* root = GetRoot();
OpPoint start_scaled_point = root->GetVisualDevice()->ScaleToDoc(start_point);
root->GenerateOnDragStart(start_scaled_point);
}
void WidgetContainer::OnDragEnter(CoreView* view, OpDragObject* drag_object, const OpPoint& point, ShiftKeyState modifiers)
{
g_drag_manager->OnDragEnter();
OpPoint scaled_point = root->GetVisualDevice()->ScaleToDoc(point);
OnDragMove(view, drag_object, scaled_point, modifiers);
}
void WidgetContainer::OnDragCancel(CoreView* view, OpDragObject* drag_object, ShiftKeyState modifiers)
{
GetRoot()->GenerateOnDragCancel(drag_object);
// Notify a source that d'n'd has been cancelled.
CoreViewDragListener* dl = g_drag_manager->GetOriginDragListener();
if (dl && dl != this)
dl->OnDragCancel(view, drag_object, modifiers);
else
g_drag_manager->StopDrag(TRUE);
}
/***********************************************************************************
**
** OnDragLeave
**
***********************************************************************************/
void WidgetContainer::OnDragLeave(CoreView* view, OpDragObject* drag_object, ShiftKeyState modifiers)
{
GetRoot()->GenerateOnDragLeave(drag_object);
// The current target (the one we enters instead) should change this.
drag_object->SetDropType(DROP_NONE);
drag_object->SetVisualDropType(DROP_NONE);
GetWindow()->SetCursor(CURSOR_NO_DROP);
}
/***********************************************************************************
**
** OnDragMove
**
***********************************************************************************/
void WidgetContainer::OnDragMove(CoreView* view, OpDragObject* drag_object, const OpPoint& point, ShiftKeyState modifiers)
{
if (!drag_object->IsInProtectedMode())
{
OpWidget* root = GetRoot();
OpPoint scaled_point = root->GetVisualDevice()->ScaleToDoc(point);
root->GenerateOnDragMove(drag_object, scaled_point);
}
else
{
drag_object->SetDropType(DROP_NONE);
drag_object->SetVisualDropType(DROP_NONE);
GetWindow()->SetCursor(CURSOR_NO_DROP);
}
}
/***********************************************************************************
**
** OnDragDrop
**
***********************************************************************************/
void WidgetContainer::OnDragDrop(CoreView* view, OpDragObject* drag_object, const OpPoint& point, ShiftKeyState modifiers)
{
OpWidget* drag_widget = g_widget_globals->drag_widget;
OpPoint scaled_point = root->GetVisualDevice()->ScaleToDoc(point);
if (drag_object->GetDropType() != DROP_NONE && !drag_object->IsInProtectedMode())
{
OpWidget* root = GetRoot();
root->GenerateOnDragDrop(drag_object, scaled_point);
}
else
OnDragLeave(view, drag_object, modifiers);
// Notify a source that d'n'd has ended.
CoreViewDragListener* dl = g_drag_manager->GetOriginDragListener();
if (dl)
dl->OnDragEnd(view, drag_object, point, modifiers);
else
OnDragEnd(view, drag_object, point, modifiers);
if (drag_widget)
{
OpRect rect = drag_widget->GetRect(TRUE);
OpPoint translated_point(scaled_point.x - rect.x, scaled_point.y - rect.y);
drag_widget->OnSetCursor(translated_point);
}
}
void WidgetContainer::OnDragEnd(CoreView* view, OpDragObject* drag_object, const OpPoint& point, ShiftKeyState modifiers)
{
g_drag_manager->StopDrag();
}
#endif // DRAG_SUPPORT
void WidgetContainer::PrefChanged(enum OpPrefsCollection::Collections id, int pref, int newvalue)
{
#ifdef CSS_SCROLLBARS_SUPPORT
if (id == OpPrefsCollection::Display && pref == PrefsCollectionDisplay::EnableScrollbarColors)
{
GetRoot()->InvalidateAll();
}
#endif
}
#ifdef NAMED_WIDGET
/***********************************************************************************
**
** Hash (NAMED_WIDGET API) (Copied from OpGenericString8HashTable)
**
***********************************************************************************/
UINT32 OpNamedWidgetsCollection::StringHash::Hash(const void* key)
{
return static_cast<UINT32>(djb2hash_nocase(static_cast<const char*>(key)));
}
/***********************************************************************************
**
** KeysAreEqual (NAMED_WIDGET API) (Copied from OpGenericString8HashTable)
**
***********************************************************************************/
BOOL OpNamedWidgetsCollection::StringHash::KeysAreEqual(const void* key1, const void* key2)
{
const char* string1 = (const char*) key1;
const char* string2 = (const char*) key2;
return !op_stricmp(string1, string2);
}
/***********************************************************************************
**
** NameChanging (NAMED_WIDGET API)
**
***********************************************************************************/
OP_STATUS OpNamedWidgetsCollection::ChangeName(OpWidget * widget, const OpStringC8 & name)
{
OP_ASSERT(widget);
if(!widget)
return OpStatus::ERR;
if (widget->packed.added_to_name_collection)
RETURN_IF_ERROR(WidgetRemoved(widget));
RETURN_IF_ERROR(widget->m_name.Set(name));
if (widget->packed.added_to_name_collection)
RETURN_IF_ERROR(WidgetAdded(widget));
return OpStatus::OK;
}
/***********************************************************************************
**
** WidgetAdded (NAMED_WIDGET API)
**
***********************************************************************************/
OP_STATUS OpNamedWidgetsCollection::WidgetAdded(OpWidget * child)
{
OP_ASSERT(child);
if(!child)
return OpStatus::ERR;
OP_STATUS status = OpStatus::OK;
if(child->HasName())
{
status = m_named_widgets.Add((void *) child->GetName().CStr(), (void *) child);
#ifdef DEBUG_ENABLE_OPASSERT
if (status == OpStatus::ERR)
{
OpWidget * widget = 0;
m_named_widgets.GetData((void *) child->GetName().CStr(), (void**) &widget);
if (widget)
widget->m_has_duplicate_named_widget = TRUE;
}
#endif // DEBUG_ENABLE_OPASSERT
}
return status;
}
/***********************************************************************************
**
** WidgetRemoved (NAMED_WIDGET API)
**
***********************************************************************************/
OP_STATUS OpNamedWidgetsCollection::WidgetRemoved(OpWidget * child)
{
OP_ASSERT(child);
if(!child)
return OpStatus::ERR;
OP_STATUS status = OpStatus::OK;
if(child->HasName())
{
OpWidget * widget = 0;
status = m_named_widgets.Remove((void *) child->GetName().CStr(), (void**) &widget);
}
return status;
}
/***********************************************************************************
**
** GetWidgetByName (NAMED_WIDGET API)
**
***********************************************************************************/
OpWidget* OpNamedWidgetsCollection::GetWidgetByName(const OpStringC8 & name)
{
OpWidget * widget = 0;
// Calling GetWidgetByName with an empty name is an error
OP_ASSERT(name.HasContent());
if(name.HasContent())
m_named_widgets.GetData((void *) name.CStr(), (void**) &widget);
OP_ASSERT(!widget || !widget->m_has_duplicate_named_widget);
return widget;
}
#endif // NAMED_WIDGET
|
#include <iostream>
#include <string>
#include "Player.h"
using namespace std;
string playerName;
char token;
Player::Player(){
}
Player::Player(char _token){
token = _token;
}
void Player::setName(string name){
playerName = name;
return;
}
string Player::getName(){
return playerName;
}
char Player::getToken(){
return token;
}
string Player::update(){
string input;
cout << playerName << "'s turn: ";
cin >> input;
return input;
}
|
#include <ros/ros.h>
#include <sstream>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/point_cloud_conversion.h>
class VeloSubscribetoPCL
{
public:
VeloSubscribetoPCL()
{
this->subscriber = this->nh.subscribe("/ce30_points", 10, &VeloSubscribetoPCL::SubVelodyne, this);
this->publisher = this->nh.advertise<sensor_msgs::PointCloud2> ("output", 1);
}
void SubVelodyne(const sensor_msgs::PointCloud &cloud_msg)
{
sensor_msgs::PointCloud2 output;
sensor_msgs::convertPointCloudToPointCloud2(cloud_msg, output);
this->publisher.publish(output);
}
private:
ros::NodeHandle nh;
ros::Subscriber subscriber;
ros::Publisher publisher;
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "talker");
VeloSubscribetoPCL VeloSubscribetoPCL;
ros::spin();
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2009 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 HAS_SET_HTTP_DATA
#include "modules/upload/upload.h"
#include "modules/formats/hdsplit.h"
#include "modules/util/handy.h"
#include "modules/olddebug/tstdump.h"
#include "modules/url/tools/arrays.h"
#define CONST_KEYWORD_ARRAY(name) PREFIX_CONST_ARRAY(static, KeywordIndex, name, upload)
#define CONST_KEYWORD_ENTRY(x,y) CONST_DOUBLE_ENTRY(keyword, x, index, y)
#define CONST_KEYWORD_END(name) CONST_END(name)
CONST_KEYWORD_ARRAY(Upload_untrusted_headers_HTTP)
CONST_KEYWORD_ENTRY(NULL, FALSE)
CONST_KEYWORD_ENTRY("Accept",TRUE)
CONST_KEYWORD_ENTRY("Accept-Charset",TRUE)
CONST_KEYWORD_ENTRY("Accept-Encoding",TRUE)
CONST_KEYWORD_ENTRY("Authorization",TRUE)
CONST_KEYWORD_ENTRY("Cache-Control",TRUE)
CONST_KEYWORD_ENTRY("Connection",TRUE)
CONST_KEYWORD_ENTRY("Content-Length",TRUE)
CONST_KEYWORD_ENTRY("Content-Transfer-Encoding",TRUE)
CONST_KEYWORD_ENTRY("Date",TRUE)
CONST_KEYWORD_ENTRY("Expect",TRUE)
CONST_KEYWORD_ENTRY("Host",TRUE)
CONST_KEYWORD_ENTRY("If-Match",TRUE)
CONST_KEYWORD_ENTRY("If-Modified-Since",TRUE)
CONST_KEYWORD_ENTRY("If-None-Match",TRUE)
CONST_KEYWORD_ENTRY("If-Range",TRUE)
CONST_KEYWORD_ENTRY("If-Unmodified-Since",TRUE)
CONST_KEYWORD_ENTRY("Keep-Alive",TRUE)
CONST_KEYWORD_ENTRY("Pragma",TRUE)
CONST_KEYWORD_ENTRY("Proxy-Authorization",TRUE)
CONST_KEYWORD_ENTRY("Referer",TRUE)
CONST_KEYWORD_ENTRY("TE",TRUE)
CONST_KEYWORD_ENTRY("Trailer",TRUE)
CONST_KEYWORD_ENTRY("Transfer-Encoding",TRUE)
CONST_KEYWORD_ENTRY("Upgrade",TRUE)
CONST_KEYWORD_ENTRY("User-Agent",TRUE)
CONST_KEYWORD_END(Upload_untrusted_headers_HTTP)
CONST_KEYWORD_ARRAY(Upload_untrusted_headers_Bcc)
CONST_KEYWORD_ENTRY(NULL, FALSE)
CONST_KEYWORD_ENTRY("Bcc",TRUE)
CONST_KEYWORD_END(Upload_untrusted_headers_Bcc)
CONST_KEYWORD_ARRAY(Upload_untrusted_headers_HTTPContentType)
CONST_KEYWORD_ENTRY(NULL, FALSE)
CONST_KEYWORD_ENTRY("Accept",TRUE)
CONST_KEYWORD_ENTRY("Accept-Charset",TRUE)
CONST_KEYWORD_ENTRY("Accept-Encoding",TRUE)
CONST_KEYWORD_ENTRY("Accept-Language",TRUE)
//CONST_KEYWORD_ENTRY("Authorization",TRUE)
CONST_KEYWORD_ENTRY("Cache-Control",TRUE)
CONST_KEYWORD_ENTRY("Connection",TRUE)
CONST_KEYWORD_ENTRY("Content-Length",TRUE)
CONST_KEYWORD_ENTRY("Content-Transfer-Encoding",TRUE)
CONST_KEYWORD_ENTRY("Content-Type",TRUE)
CONST_KEYWORD_ENTRY("Expect",TRUE)
CONST_KEYWORD_ENTRY("Host",TRUE)
CONST_KEYWORD_ENTRY("If-Match",TRUE)
CONST_KEYWORD_ENTRY("If-Modified-Since",TRUE)
CONST_KEYWORD_ENTRY("If-None-Match",TRUE)
CONST_KEYWORD_ENTRY("If-Range",TRUE)
CONST_KEYWORD_ENTRY("If-Unmodified-Since",TRUE)
CONST_KEYWORD_ENTRY("Keep-Alive",TRUE)
CONST_KEYWORD_ENTRY("Pragma",TRUE)
CONST_KEYWORD_ENTRY("Proxy-Authorization",TRUE)
CONST_KEYWORD_ENTRY("Referrer",TRUE)
CONST_KEYWORD_ENTRY("TE",TRUE)
CONST_KEYWORD_ENTRY("Trailer",TRUE)
CONST_KEYWORD_ENTRY("Transfer-Encoding",TRUE)
CONST_KEYWORD_ENTRY("Upgrade",TRUE)
CONST_KEYWORD_ENTRY("User-Agent",TRUE)
CONST_KEYWORD_END(Upload_untrusted_headers_HTTPContentType)
Header_List::Header_List()
{
}
void Header_List::SetSeparator(Header_Parameter_Separator sep)
{
Header_Item *item = First();
while(item)
{
item->SetSeparator(sep);
item = item->Suc();
}
}
void Header_List::InitL(const char **header_names, Header_Parameter_Separator sep)
{
if(header_names)
{
OpStackAutoPtr<Header_Item> item(NULL);
while(*header_names)
{
item.reset(FindHeader(*header_names,TRUE));
if(!item.get())
{
item.reset(OP_NEW_L(Header_Item, (sep)));
item->InitL(/*OpStringC8*/(*header_names));
item->Into(this);
}
item.release();
header_names++;
}
}
}
Header_Item *Header_List::FindHeader(const OpStringC8 &header_ref, BOOL last)
{
if(header_ref.IsEmpty())
return NULL;
if (last)
{
for (Header_Item *item = Last(); item; item = item->Pred())
if(item->GetName().CompareI(header_ref) == 0)
return item;
}
else
{
for (Header_Item *item = First(); item; item = item->Suc())
if(item->GetName().CompareI(header_ref) == 0)
return item;
}
return NULL;
}
Header_Item *Header_List::InsertHeaderL(const OpStringC8 &new_header_name, Header_InsertPoint insert_point, Header_Parameter_Separator sep, const OpStringC8 &header_ref)
{
OpStackAutoPtr<Header_Item> item(NULL);
item.reset(OP_NEW_L(Header_Item, (sep)));
item->InitL(new_header_name);
InsertHeader(item.get(), insert_point, header_ref);
return item.release();
}
void Header_List::InsertHeader(Header_Item *new_header, Header_InsertPoint insert_point, const OpStringC8 &header_ref)
{
Header_Item *insert_item;
if(new_header == NULL)
return;
if(new_header->InList())
new_header->Out();
switch(insert_point)
{
case HEADER_INSERT_SORT_BEFORE:
case HEADER_INSERT_BEFORE:
insert_item = FindHeader(header_ref, FALSE);
if(insert_item)
{
new_header->Precede(insert_item);
break;
}
case HEADER_INSERT_FRONT:
new_header->IntoStart(this);
break;
case HEADER_INSERT_SORT_AFTER:
case HEADER_INSERT_AFTER:
insert_item = FindHeader(header_ref, TRUE);
if(insert_item)
{
new_header->Follow(insert_item);
break;
}
case HEADER_INSERT_LAST:
default:
new_header->Into(this);
break;
}
}
void Header_List::InsertHeaders(Header_List &new_header, Header_InsertPoint insert_point, const OpStringC8 &header_ref, BOOL remove_existing)
{
Header_Item *insert_item, *insert_item2, *item, *temp, *temp2;
if (remove_existing)
for (item = new_header.First(); item; item = item->Suc())
RemoveHeader(item->GetName());
item = new_header.First();
if(!item)
return;
switch(insert_point)
{
case HEADER_INSERT_SORT_BEFORE:
while(item)
{
temp = item->Suc();
insert_item2 = FindHeader(item->GetName(), FALSE);
if(insert_item2)
{
item->Out();
item->Precede(insert_item2);
item = temp;
while(item)
{
temp2 = item->Suc();
if(item->GetName().CompareI(insert_item2->GetName()) == 0)
{
item->Out();
item->Precede(insert_item2);
if(item == temp)
temp = temp2;
}
item = temp2;
}
}
item = temp;
}
item = new_header.First();
case HEADER_INSERT_BEFORE:
insert_item = FindHeader(header_ref, FALSE);
if(insert_item)
{
item->Out();
item->Precede(insert_item);
insert_item = item;
break;
}
case HEADER_INSERT_FRONT:
item->Out();
item->IntoStart(this);
insert_item = item;
break;
case HEADER_INSERT_SORT_AFTER:
while(item)
{
temp = item->Suc();
insert_item2 = FindHeader(item->GetName(), TRUE);
if(insert_item2)
{
item->Out();
item->Follow(insert_item2);
insert_item2 = item;
item = temp;
while(item)
{
temp2 = item->Suc();
if(item->GetName().CompareI(insert_item2->GetName()) == 0)
{
item->Out();
item->Follow(insert_item2);
insert_item2 = item;
if(item == temp)
temp = temp2;
}
item = temp2;
}
}
item = temp;
}
item = new_header.First();
// fall-through
case HEADER_INSERT_AFTER:
insert_item = FindHeader(header_ref, TRUE);
if(insert_item)
{
item->Out();
item->Follow(insert_item);
insert_item = item;
break;
}
case HEADER_INSERT_LAST:
default:
item->Out();
item->Into(this);
insert_item = item;
break;
}
while((item = new_header.First()) != NULL)
{
item->Out();
item->Follow(insert_item);
insert_item = item;
}
}
void Header_List::AddParameterL(const OpStringC8 &header_name, const OpStringC8 &p_value)
{
Header_Item *item;
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
if(p_value.Length())
item->AddParameterL(p_value);
}
void Header_List::SetSeparatorL(const OpStringC8 &header_name, Header_Parameter_Separator sep)
{
Header_Item *item;
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
item->SetSeparator(sep);
}
void Header_List::AddParameterL(const OpStringC8 &header_name, const OpStringC8 &p_name, const OpStringC8 &p_value, BOOL quote_value)
{
Header_Item *item;
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
if(p_value.Length() || p_name.Length())
item->AddParameterL(p_name, p_value, quote_value);
}
void Header_List::AddParameterL(const OpStringC8 &header_name, Header_Parameter_Base *param)
{
OpStackAutoPtr<Header_Parameter_Base> param2(param);
Header_Item *item;
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
item->AddParameter(param2.release());
}
void Header_List::ClearHeader(const OpStringC8 &header_name)
{
Header_Item *item = FindHeader(header_name, TRUE);
if(item != NULL)
item->ClearParameters();
}
void Header_List::RemoveHeader(const OpStringC8 &header_name)
{
Header_Item *item;
while ((item = FindHeader(header_name, FALSE)) != NULL)
OP_DELETE(item);
}
void Header_List::ClearAndAddParameterL(const OpStringC8 &header_name, const OpStringC8 &p_value)
{
Header_Item *item;
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
item->ClearParameters();
if(p_value.Length())
item->AddParameterL(p_value);
}
#ifdef UPLOAD_CLEARADD_PARAMETER_SEP
void Header_List::ClearAndSetSeparatorL(const OpStringC8 &header_name, Header_Parameter_Separator sep)
{
Header_Item *item;
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
item->ClearParameters();
item->SetSeparator(sep);
}
#endif
#ifdef UPLOAD_CLEARADD_PARAMETER_PAIR
void Header_List::ClearAndAddParameterL(const OpStringC8 &header_name, const OpStringC8 &p_name, const OpStringC8 &p_value, BOOL quote_value)
{
Header_Item *item;
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
item->ClearParameters();
if(p_value.Length() || p_name.Length())
item->AddParameterL(p_name, p_value, quote_value);
}
#endif
#ifdef UPLOAD_CLEARADD_PARAMETER
void Header_List::ClearAndAddParameterL(const OpStringC8 &header_name, Header_Parameter_Base *param)
{
OpStackAutoPtr<Header_Parameter_Base> param2(param);
Header_Item *item;
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
item->ClearParameters();
item->AddParameter(param2.release());
}
#endif
#ifdef URL_UPLOAD_QP_SUPPORT
void Header_List::AddQuotedPrintableParameterL(const OpStringC8 &header_name, const OpStringC8 &p_name, const OpStringC8 &p_value, const OpStringC8 &charset, Header_Encoding encoding)
{
Header_Item *item;
OpStackAutoPtr<Header_QuotedPrintable_Parameter> new_param ( OP_NEW_L(Header_QuotedPrintable_Parameter, ()));
new_param->InitL(p_name, p_value, charset, encoding, TRUE);
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
item->AddParameter(new_param.release());
}
void Header_List::AddQuotedPrintableParameterL(const OpStringC8 &header_name, const OpStringC8 &p_name, const OpStringC16 &p_value, const OpStringC8 &charset, Header_Encoding encoding)
{
Header_Item *item;
OpStackAutoPtr<Header_QuotedPrintable_Parameter> new_param ( OP_NEW_L(Header_QuotedPrintable_Parameter, ()));
new_param->InitL(p_name, p_value, charset, encoding, TRUE);
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
item->AddParameter(new_param.release());
}
#endif
#ifdef URL_UPLOAD_RFC_2231_SUPPORT
void Header_List::AddRFC2231ParameterL(const OpStringC8 &header_name, const OpStringC8 &p_name, const OpStringC8 &p_value, const OpStringC8 &charset)
{
Header_Item *item;
OpStackAutoPtr<Header_RFC2231_Parameter> new_param ( OP_NEW_L(Header_RFC2231_Parameter, ()));
new_param->InitL(p_name, p_value, charset);
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
item->AddParameter(new_param.release());
}
void Header_List::AddRFC2231ParameterL(const OpStringC8 &header_name, const OpStringC8 &p_name, const OpStringC16 &p_value, const OpStringC8 &charset)
{
Header_Item *item;
OpStackAutoPtr<Header_RFC2231_Parameter> new_param ( OP_NEW_L(Header_RFC2231_Parameter, ()));
new_param->InitL(p_name, p_value, charset);
item = FindHeader(header_name, TRUE);
if(item == NULL)
item = InsertHeaderL(header_name);
item->AddParameter(new_param.release());
}
#endif // URL_UPLOAD_RFC_2231_SUPPORT
#ifdef UPLOAD_HDR_IS_ENABLED
BOOL Header_List::HeaderIsEnabled(const OpStringC8 &header)
{
Header_Item *item;
item = FindHeader(header, TRUE);
return !item || item->IsEnabled(); // default for all is enabled
}
#endif
void Header_List::HeaderSetEnabledL(const OpStringC8 &header, BOOL flag)
{
Header_Item *item = First();
BOOL found = FALSE;
while(item)
{
if(item->GetName().CompareI(header) == 0)
{
found = TRUE;
item->SetEnabled(flag);
}
item = item->Suc();
}
if(!found)
{
item = InsertHeaderL(header);
item->SetEnabled(flag);
}
}
uint32 Header_List::CalculateLength()
{
uint32 len=0;
Header_Item *item = First();
while(item)
{
len += item->CalculateLength();
item = item->Suc();
}
return len;
}
char *Header_List::OutputHeaders(char *target)
{
Header_Item *item = First();
*target = '\0'; // Null terminate in case of no output
while(item)
{
target = item->OutputHeader(target);
item = item->Suc();
}
return target;
}
uint32 Header_List::ExtractHeadersL(const unsigned char *src, uint32 len, BOOL use_all, Header_Protection_Policy policy, const KeywordIndex *excluded_headers, int excluded_list_len)
{
if(src == NULL || len == 0)
return 0;
const unsigned char *pos = src;
unsigned char token;
uint32 i;
for(i=0;i< len;i++)
{
token = *(pos++);
if(token < 0x20)
{
if(token == '\n')
{
if(i == len-1 || *pos == '\n')
break;
if(*pos != '\r')
continue;
i++;
pos++;
if(i == len-1 || *pos == '\n')
break;
}
else if(token != '\t' && token != '\r')
{
return 0;
break;
}
}
}
if(use_all || i < len)
{
const KeywordIndex *keywords_list = NULL;
int keywords_len = 0;
ANCHORD(HeaderList, untrusted_headers);
ANCHORD(OpString8, src_str);
src_str.SetL((const char *)src, i+1);
untrusted_headers.SetValueL(src_str.CStr());
switch(policy)
{
case HEADER_REMOVE_HTTP:
keywords_list =g_Upload_untrusted_headers_HTTP;
keywords_len = (int)CONST_ARRAY_SIZE(upload, Upload_untrusted_headers_HTTP);
break;
case HEADER_REMOVE_HTTP_CONTENT_TYPE:
keywords_list =g_Upload_untrusted_headers_HTTPContentType;
keywords_len = (int)CONST_ARRAY_SIZE(upload, Upload_untrusted_headers_HTTPContentType);
break;
case HEADER_REMOVE_BCC:
keywords_list =g_Upload_untrusted_headers_Bcc;
keywords_len = (int)CONST_ARRAY_SIZE(upload, Upload_untrusted_headers_Bcc);
break;
}
HeaderEntry *next_item = untrusted_headers.First();
HeaderEntry *item;
while(next_item)
{
item = next_item;
next_item = next_item->Suc();
if(item->Name())
{
if (policy == HEADER_REMOVE_HTTP && op_strnicmp(item->Name(), "sec-", 4) == 0)
continue;// Skip, DO NOT add, untrusted header that starts with "sec-", as these are reserved for websockets.
if(CheckKeywordsIndex(item->Name(), keywords_list, keywords_len) > 0)
continue; // Skip, DO NOT add, untrusted header
if(excluded_headers && excluded_list_len &&
CheckKeywordsIndex(item->Name(), excluded_headers, excluded_list_len) > 0)
continue; // Skip, DO NOT add, untrusted header
}
AddParameterL(item->Name(), item->Value());
}
if(!use_all)
i++;
}
return i+1;
}
#endif // HTTP_data
|
#include "pch.h"
#include <Kore/System.h>
#include <Kore/Application.h>
#include <Kore/Input/Keyboard.h>
#include <Kore/Log.h>
using namespace Kore;
bool System::handleMessages() {
return true;
}
void System::swapBuffers() {
}
void* System::createWindow() {
return nullptr;
}
void System::destroyWindow() {
}
int System::screenWidth() {
return Application::the()->width();
}
int System::screenHeight() {
return Application::the()->height();
}
int System::desktopWidth() {
return 800;
}
int System::desktopHeight() {
return 600;
}
namespace {
const char* savePath = nullptr;
void getSavePath() {
}
}
const char* System::savePath() {
if (::savePath == nullptr) getSavePath();
return ::savePath;
}
//int main(int argc, char** argv) {
// return 0;
//}
namespace {
int mouseX, mouseY;
bool keyboardShown = false;
}
vec2i System::mousePos() {
return vec2i(mouseX, mouseY);
}
void System::changeResolution(int width, int height, bool fullscreen) {
}
void System::showKeyboard() {
keyboardShown = true;
}
void System::hideKeyboard() {
keyboardShown = false;
}
bool System::showsKeyboard() {
return keyboardShown;
}
void System::loadURL(const char* url) {
}
const char* System::systemId() {
return "Blender";
}
namespace {
const char* videoFormats[] = { "ogv", nullptr };
}
const char** Kore::System::videoFormats() {
return ::videoFormats;
}
void System::showWindow() {
}
void System::setTitle(const char* title) {
}
#include <mach/mach_time.h>
double System::frequency() {
mach_timebase_info_data_t info;
mach_timebase_info(&info);
return (double)info.denom / (double)info.numer / 1e-9;
}
System::ticks System::timestamp() {
return mach_absolute_time();
}
|
#include "Cd.h"
class Classic :public Cd
{
char main[50];
public:
Classic(const char* m, const char* performers, const char* label, int se, double pt);
Classic(const char* m, const Cd& d);
Classic();
void Report() const;
};
|
#pragma once
#include "Material.h"
#include "Lambertian.h"
class Matte : public Material
{
public:
BRDF *ambientBRDF;
BRDF *diffuseBRDF;
BRDF* getAmbientBRDF();
BRDF* getDiffuseBRDF();
Matte();
~Matte();
};
|
/*
* File: maildrop.h
* Author: Wouter Van Rossem
*
*/
#ifndef _MAILDROP_H
#define _MAILDROP_H
#include <dvthread/thread.h>
#include <vector>
#include <string>
#include <fstream>
#include <sys/types.h>
#include <dirent.h>
#include "message.h"
/** The Maildrop class represents a maildrop of a user.
* All the messages are stored in a vector.
* The path to the folder of the maildrop is stored
*/
class Maildrop
{
public:
/** Constructor for Maildrop
* @param folderpath String indicating where the folder is located
* @exception std::runtime_error If the folder cannot be opened
*/
Maildrop (std::string folderpath);
/** Destructor for Maildrop
* This will delete all the messages marked as deleted
*/
virtual ~Maildrop ();
/** Add a new message to the maildrop
* @param message The message to add to the maildrop
*/
void add_message (Message* message);
/** Retrieve a message from the maildrop
* @param msg_nr The number of the message
* @return The actual message if found
* @return false if the message is not found
*/
Message* retrieve_message (int msg_nr) const;
/** Delete a message from the maildrop
* This does not actually delete the message but marks it as deleted
* @param msg_nr The number of the message
* @return A bool indicating if the operation has succeeded
*/
bool delete_message (int msg_nr);
/**
* @param deleted Count messages marked as deleted?
* @return the number of messages in the maildrop
*/
int nr_of_messages (bool deleted = false) const;
/** Return the size of the maildrop
* @return The size of the maildrop in octets
*/
unsigned long size () const;
/** Get all the messages from the maildrop (including the ones marked
* as deleted or not).
* @param deleted Return messages marked as deleted
* @return A vector containing the messages
*/
std::vector<Message*> messages (bool deleted = false) const;
private:
/** Private copy constructor */
Maildrop (const Maildrop& orig);
/* Vector containning all the messages in the maildrop */
std::vector<Message*> _messages;
/* String */
std::string _folder_path;
};
#endif /* _MAILDROP_H */
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#define INF (1<<20)
#define MAX 101
using namespace std;
class YetAnotherIncredibleMachine {
public:
int countWays(vector <int> platformMount, vector <int> platformLength, vector <int> balls)
{
long long ans = 1;
for (int i=0; i<platformLength.size(); ++i) {
int left=-1;
for (int j=0; j<=platformLength[i]; ++j) {
left = platformMount[i]-j;
if (find(balls.begin(), balls.end(), left) != balls.end()) {
++left;
break;
}
}
int right=-1;
for (int j=0; j<=platformLength[i]; ++j) {
right = platformMount[i]+j;
if (find(balls.begin(), balls.end(), right) != balls.end()) {
--right;
break;
}
}
int ways = (right-left) - platformLength[i] + 1;
if (ways < 1) {
return 0;
}
ans = (ans*ways)%1000000009;
}
return (int)ans;
}
};
|
// Copyright (C) 2012 - 2013 Mihai Preda
#include "Map.h"
#include "Array.h"
#include "String.h"
#include "Value.h"
#include "Object.h"
#include "GC.h"
#include "NameValue.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdarg.h>
void Map::traverse(GC *gc) {
int sz = size();
gc->markValVect(valBuf(), sz);
gc->markValVect(keyBuf(), sz);
}
Map::Map() {
((Object *) this)->setType(O_MAP);
}
Map::~Map() {
}
Value Map::makeMap(GC *gc, ...) {
va_list ap;
va_start(ap, gc);
Map *m = Map::alloc(gc);
while (true) {
char *name = va_arg(ap, char*);
if (!name) { break; }
// fprintf(stderr, "%s\n", name);
Value v = va_arg(ap, Value);
m->indexSet(String::value(gc, name), v);
}
va_end(ap);
return VAL_OBJ(m);
}
Value Map::keysField(VM *vm, int op, void *data, Value *stack, int nArgs) {
return VNIL;
}
bool Map::equals(Map *o) {
const int sz = size();
if (sz != o->size()) { return false; }
for (Value *pk = keyBuf(), *end=pk+sz, *pv=valBuf(); pk < end; ++pk, ++pv) {
if (!::equals(*pv, o->indexGet(*pk))) { return false; }
}
return true;
}
Value Map::remove(Value key) {
const int pos = index.remove(key);
if (pos < 0) {
return VNIL;
} else {
Value val = vals.get(pos);
Value top = vals.pop();
if (pos < index.size()) {
vals.setDirect(pos, top);
}
return val;
}
}
/*
Value Map::getOrAdd(Value key, Value v) {
const int pos = index.add(key);
return pos >= 0 ? vals.get(pos) : (vals.push(v), v);
}
*/
void Map::setVectors(Vector<Value> *keys, Vector<Value> *vals) {
const int sz = keys->size();
assert(vals->size() == sz);
setArrays(keys->buf(), vals->buf(), sz);
}
void Map::setArrays(Value *keys, Value *vals, int size) {
for (Value *pk=keys, *end=keys+size, *pv=vals; pk < end; ++pk, ++pv) {
indexSet(*pk, *pv);
}
}
Map *Map::copy(GC *gc) {
Map *m = alloc(gc, size());
m->setArrays(keyBuf(), valBuf(), size());
return m;
}
bool Map::indexSet(Value key, Value v) {
if (IS_NIL(v)) {
remove(key);
} else {
const int pos = index.add(key);
if (pos >= 0) {
vals.setDirect(pos, v);
} else {
vals.push(v);
}
}
return true;
}
Value Map::indexGet(Value key) {
const int pos = index.getPos(key);
return pos < 0 ? VNIL : vals.get(pos);
}
void Map::add(Value v) {
ERR(!(IS_MAP(v)), E_ADD_NOT_COLLECTION);
Map *m = MAP(v);
setArrays(m->keyBuf(), m->valBuf(), m->size());
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2009 Mark Borgerding mark a borgerding net
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include <bench/BenchUtil.h>
#include <complex>
#include <vector>
#include <Eigen/Core>
#include <unsupported/Eigen/FFT>
using namespace Eigen;
using namespace std;
template <typename T>
string nameof();
template <> string nameof<float>() {return "float";}
template <> string nameof<double>() {return "double";}
template <> string nameof<long double>() {return "long double";}
#ifndef TYPE
#define TYPE float
#endif
#ifndef NFFT
#define NFFT 1024
#endif
#ifndef NDATA
#define NDATA 1000000
#endif
using namespace Eigen;
template <typename T>
void bench(int nfft,bool fwd,bool unscaled=false, bool halfspec=false)
{
typedef typename NumTraits<T>::Real Scalar;
typedef typename std::complex<Scalar> Complex;
int nits = NDATA/nfft;
vector<T> inbuf(nfft);
vector<Complex > outbuf(nfft);
FFT< Scalar > fft;
if (unscaled) {
fft.SetFlag(fft.Unscaled);
cout << "unscaled ";
}
if (halfspec) {
fft.SetFlag(fft.HalfSpectrum);
cout << "halfspec ";
}
std::fill(inbuf.begin(),inbuf.end(),0);
fft.fwd( outbuf , inbuf);
BenchTimer timer;
timer.reset();
for (int k=0;k<8;++k) {
timer.start();
if (fwd)
for(int i = 0; i < nits; i++)
fft.fwd( outbuf , inbuf);
else
for(int i = 0; i < nits; i++)
fft.inv(inbuf,outbuf);
timer.stop();
}
cout << nameof<Scalar>() << " ";
double mflops = 5.*nfft*log2((double)nfft) / (1e6 * timer.value() / (double)nits );
if ( NumTraits<T>::IsComplex ) {
cout << "complex";
}else{
cout << "real ";
mflops /= 2;
}
if (fwd)
cout << " fwd";
else
cout << " inv";
cout << " NFFT=" << nfft << " " << (double(1e-6*nfft*nits)/timer.value()) << " MS/s " << mflops << "MFLOPS\n";
}
int main(int argc,char ** argv)
{
bench<complex<float> >(NFFT,true);
bench<complex<float> >(NFFT,false);
bench<float>(NFFT,true);
bench<float>(NFFT,false);
bench<float>(NFFT,false,true);
bench<float>(NFFT,false,true,true);
bench<complex<double> >(NFFT,true);
bench<complex<double> >(NFFT,false);
bench<double>(NFFT,true);
bench<double>(NFFT,false);
bench<complex<long double> >(NFFT,true);
bench<complex<long double> >(NFFT,false);
bench<long double>(NFFT,true);
bench<long double>(NFFT,false);
return 0;
}
|
#include "dbcached.hpp"
#include "utils/process_utils.hpp"
namespace nora {
namespace dbcache {
dbcached::dbcached(const shared_ptr<service_thread>& st) {
if (!st_) {
st_ = make_shared<service_thread>("dbcached");
st_->start();
}
scene_ = make_shared<scene>("dbcache-scene", st_);
}
void dbcached::start() {
register_signals();
auto ptt = PTTS_GET_COPY(options, 1u);
scene_->stop_cb_ = [this] {
stop();
};
scene_->start(ptt.scened_dbcached_ipport().ip(), (unsigned short)ptt.scened_dbcached_ipport().port());
add_instance_count_timer();
}
void dbcached::add_instance_count_timer() {
ADD_TIMER(
st_,
([this] (auto canceled, const auto& timer) {
if (!canceled) {
instance_counter::instance().print();
this->add_instance_count_timer();
}
}),
5s);
}
void dbcached::register_signals() {
if (!signals_) {
signals_ = make_unique<ba::signal_set>(st_->get_service());
signals_->add(SIGBUS);
signals_->add(SIGSEGV);
signals_->add(SIGABRT);
signals_->add(SIGFPE);
signals_->add(SIGTERM);
signals_->add(SIGINT);
auto ptt = PTTS_GET_COPY(options, 1u);
if (ptt.minicore()) {
signals_->add(SIGBUS);
signals_->add(SIGSEGV);
signals_->add(SIGABRT);
signals_->add(SIGFPE);
}
}
signals_->async_wait(
[this] (auto ec, auto sig) {
if (ec) {
return;
}
if (sig == SIGTERM || sig == SIGINT) {
DBCACHE_ILOG << "received SIGTERM or SIGINT, stop";
signals_->cancel();
if (scene_) {
scene_->try_stop();
} else {
this->stop();
}
} else if (sig == SIGBUS || sig == SIGSEGV || sig == SIGABRT || sig == SIGFPE) {
write_stacktrace_to_file("dbcached");
exit(0);
} else {
this->register_signals();
}
});
}
void dbcached::stop() {
exit(0);
}
}
}
|
#include <iostream>
#include <string.h>
#include "Clase.h"
using namespace std;
Persoana::Persoana()
{
id = -1;
nume = NULL;
nr_obiecte++;
}
Persoana::Persoana(int numar)
{
id = numar;
nume = NULL;
nr_obiecte++;
}
Persoana::Persoana(char* denumire)
{
int nr = strlen(denumire);
nume = new char[ nr + 1];
for(int i = 0; i < nr ; i++ )
nume[i] = denumire[i];
id = -1;
nr_obiecte++;
}
Persoana::Persoana(int numar, char* denumire)
{
id = numar;
int nr = strlen(denumire);
nume = new char[ nr + 1];
for(int i = 0; i < nr ; i++ )
nume[i] = denumire[i];
nr_obiecte++;
}
Persoana::Persoana ( const Persoana& copie)
{
id = copie.id;
int nr = strlen(copie.nume);
nume = new char[ nr + 1];
for(int i = 0; i < nr ; i++ )
nume[i] = copie.nume[i];
nr_obiecte++;
}
const Persoana& Persoana::operator=(const Persoana& P)
{
if(this != &P )
{
id = P.id;
set_nume(P.nume);
}
return *this;
}
istream& operator>>(istream& i, Persoana& p)
{
cout << "Se citeste o persoana: " << endl;
cout << "ID: ";
i >> p.id;
delete [] p.nume;
cout << "Nume: ";
i >> p.nume;
cout << endl;
return i;
}
ostream& operator<<(ostream& o, const Persoana& p)
{
o << "Informatii persoana: " << endl << "ID: " << p.id << endl << "Nume: " << p.nume << endl;
return o;
}
/* Clasa Abonat */
Abonat::Abonat(char *telefon, char* denumire, int i): Persoana(i, denumire)
{
int nr = strlen(telefon);
nr_telefon = new char[nr+1];
for(int j = 0; j < nr ; j++)
nr_telefon[j] = telefon[j];
nr_obiecte++;
}
Abonat::Abonat(const Abonat& a):Persoana(a.id, a.nume)
{
int nr = strlen(a.nr_telefon);
nr_telefon = new char[nr+1];
for(int j = 0; j < nr ; j++)
nr_telefon[j] = a.nr_telefon[j];
nr_obiecte++;
}
Abonat::Abonat()
{
nr_telefon = NULL;
nr_obiecte++;
}
const Abonat& Abonat :: operator=(const Abonat& a)
{
if(this != &a)
{
id = a.id;
set_nume(a.nume);
set_nr_telefon(a.nr_telefon);
}
return *this;
}
istream& operator>>(istream& i, Abonat& p)
{
char s[256];
cout << endl << "Se citeste o persoana: " << endl;
cout << "ID: ";
i >> p.id;
cout << "Nume: ";
i.get();
i.getline(s, 256);
p.set_nume(s);
cout << "Numar de telefon: ";
i >> s;
p.set_nr_telefon(s);
return i;
}
ostream& operator<<(ostream& o, const Abonat& p)
{
o << endl << "Informatii Abonat: " << endl << "ID: " << p.id << endl << "Nume: ";
o << p.nume << endl << "Numar de telefon: " << p.nr_telefon << endl;
return o;
}
/* Clasa Abonat Skype */
Abonat_Skype::Abonat_Skype()
{
id_Skype = NULL;
nr_obiecte++;
}
Abonat_Skype::Abonat_Skype(char *telefon, char* denumire, int i, char* j): Abonat (telefon, denumire, i)
{
set_id_skype(j);
nr_obiecte++;
}
Abonat_Skype::Abonat_Skype(const Abonat_Skype& a): Abonat(a.nr_telefon, a.nume, a.id)
{
set_id_skype(a.id_Skype);
nr_obiecte++;
}
const Abonat_Skype& Abonat_Skype :: operator=(const Abonat_Skype& a)
{
if(this != &a)
{
id = a.id;
set_nume(a.nume);
set_nr_telefon(a.nr_telefon);
set_id_skype(a.id_Skype);
}
return *this;
}
istream& operator>>(istream& i, Abonat_Skype& p)
{
char s[256];
cout << endl << "Se citeste o persoana: " << endl;
cout << "ID: ";
i >> p.id;
cout << "Nume: ";
i.get();
i.getline(s, 256);
p.set_nume(s);
cout << "Numar de telefon: ";
i >> s;
p.set_nr_telefon(s);
cout << "ID Skype: ";
i >> s;
p.set_id_skype(s);
return i;
}
ostream& operator<<(ostream& o, const Abonat_Skype& p)
{
o << endl << "Informatii Abonat: " << endl << "ID: " << p.id << endl << "Nume: ";
o << p.nume << endl << "Numar de telefon: " << p.nr_telefon << endl << "ID Skype: " <<p.id_Skype ;
return o;
}
/* Abonat Skype Romania */
Abonat_Skype_Romania:: Abonat_Skype_Romania()
{
adresa_mail = NULL;
nr_obiecte++;
}
Abonat_Skype_Romania:: Abonat_Skype_Romania(char *denumire, char *telefon, char* mail, int i, char* j): Abonat_Skype(telefon, denumire,i,j)
{
int nr = strlen(mail);
adresa_mail = new char[nr+1];
for(int j = 0; j < nr ; j++)
adresa_mail[j] = mail[j];
adresa_mail[nr] = NULL;
nr_obiecte++;
}
Abonat_Skype_Romania::Abonat_Skype_Romania(const Abonat_Skype_Romania& a): Abonat_Skype(a.nr_telefon, a.nume,a.id,a.id_Skype)
{
int nr = strlen(a.adresa_mail);
adresa_mail = new char[nr+1];
for(int j = 0; j < nr ; j++)
adresa_mail[j] = a.adresa_mail[j];
adresa_mail[nr] = NULL;
nr_obiecte++;
}
const Abonat_Skype_Romania& Abonat_Skype_Romania :: operator=(const Abonat_Skype_Romania& a)
{
if(this != &a)
{
id = a.id;
set_nume(a.nume);
set_nr_telefon(a.nr_telefon);
set_id_skype(a.id_Skype);
set_adresa_mail(a.adresa_mail);
}
return *this;
}
istream& operator>>(istream& i, Abonat_Skype_Romania& p)
{
char s[256];
cout << endl;
cout << "Se citeste o persoana: " << endl;
cout << "ID: ";
i >> p.id;
cout << "Nume: ";
i.get();
i.getline(s, 256);
p.set_nume(s);
cout << "Numar de telefon: ";
i >> s;
p.set_nr_telefon(s);
cout << "ID Skype: ";
i >> s;
p.set_id_skype(s);
cout << "Adresa de mail: ";
i >> s;
p.set_adresa_mail(s);
return i;
}
ostream& operator<<(ostream& o, const Abonat_Skype_Romania& p)
{
o << endl << "Informatii Abonat: " << endl << endl << "ID: " << p.id << endl << "Nume: ";
o << p.nume << endl << "Numar de telefon: " << p.nr_telefon << endl << "ID Skype: " <<p.id_Skype ;
o << endl << "Adresa de mail: " << p.adresa_mail << endl;
return o;
}
/* Abonat Skype Extern */
Abonat_Skype_Extern::Abonat_Skype_Extern()
{
tara = NULL;
nr_obiecte++;
}
Abonat_Skype_Extern:: Abonat_Skype_Extern(char *denumire, char *telefon, char* t, int i, char* j): Abonat_Skype(telefon, denumire,i,j)
{
int nr = strlen(t);
tara = new char[nr+1];
for(int i = 0; i < nr ; i++)
tara[i] = t[i];
tara[nr] = NULL;
nr_obiecte++;
}
Abonat_Skype_Extern::Abonat_Skype_Extern(const Abonat_Skype_Extern &a): Abonat_Skype (a.nr_telefon, a.nume, a.id, a.id_Skype)
{
int nr = strlen(a.tara);
tara = new char[nr+1];
for(int j = 0; j < nr ; j++)
tara[j] = a.tara[j];
tara[nr] = NULL;
nr_obiecte++;
}
const Abonat_Skype_Extern& Abonat_Skype_Extern :: operator=(const Abonat_Skype_Extern& a)
{
if(this != &a)
{
id = a.id;
set_nume(a.nume);
set_nr_telefon(a.nr_telefon);
set_id_skype(a.id_Skype);
set_tara(a.tara);
}
return *this;
}
istream& operator>>(istream& i, Abonat_Skype_Extern& p)
{
char s[256];
cout << endl << "Se citeste o persoana: " << endl;
cout << "ID: ";
i >> p.id;
cout << "Nume: ";
i.get();
i.getline(s, 256);
p.set_nume(s);
cout << "Numar de telefon: ";
i >> s;
p.set_nr_telefon(s);
cout << "ID Skype: ";
i >> s;
p.set_id_skype(s);
cout << "Tara: ";
i.get();
i.getline(s, 256);
p.set_tara(s);
return i;
}
ostream& operator<<(ostream& o, const Abonat_Skype_Extern& p)
{
o << endl << "Informatii Abonat: " << endl << endl << "ID: " << p.id << endl << "Nume: ";
o << p.nume << endl << "Numar de telefon: " << p.nr_telefon << endl << "ID Skype: " <<p.id_Skype ;
o << endl << "Tara: " << p.tara << endl;
return o;
}
/* AGENDA */
Agenda::Agenda(int numar)
{
for(int i = 0; i < numar ; i++)
abonati[i] = new Abonat;
numar_abonati = numar;
}
Agenda::Agenda(const Agenda& a)
{
numar_abonati = a.numar_abonati;
for(int i = 0 ; i < numar_abonati ; i++)
{
abonati[i] = new Abonat;
*abonati[i] = *(a.abonati[i]);
}
}
Agenda::Agenda()
{
numar_abonati = 0;
abonati[0] = NULL;
}
const Agenda& Agenda :: operator=(const Agenda& a)
{
if(this != &a)
{
set_abonati(a.numar_abonati);
for(int i = 0 ; i < numar_abonati ; i++)
{
delete abonati[i];
abonati[i] = new Abonat;
*abonati[i] = *(a.abonati[i]);
}
}
return *this;
}
istream& operator>>(istream& i, Agenda& a)
{
cout << "Numar de abonati: ";
i >> a.numar_abonati;
cout << "Abonati: " << endl;
for(int j = 0 ; j < a.numar_abonati; j++)
{
cout << "Abonat[" << j << "]= ";
delete a.abonati[j];
i >> *(a.abonati[j]);
}
return i;
}
void meniu ()
{
cout << endl << "Meniu: ";
cout << endl << "1. Abonat Skype Romania";
cout << endl << "2. Abonat Skype Extern";
cout << endl;
}
int Persoana:: nr_obiecte = 0;
int main()
{
int numar_abonati, i, j;
cout << "Se da numarul de abonati: ";
cin >> numar_abonati;
Agenda ag;
Abonat_Skype_Extern* e;
Abonat_Skype_Romania* r;
for(i = 0 ; i < numar_abonati ; i++)
{
int optiune;
meniu();
cout << endl;
cout << "Alege optiune: ";
cin >> optiune;
switch(optiune)
{
case 1 :
{
r = new Abonat_Skype_Romania;
cout << "Citeste Abonat Skype Romania: " << endl;
cin >> *r;
ag[i] = r;
break;
}
case 2:
{
e = new Abonat_Skype_Extern();
cout << "Citeste Abonat Skype Extern: " << endl;
cin >> *e;
ag[i] = e;
break;
}
default:
cout << "Operatiunea aleasa nu este valida!";
if(i == 0 )
{
break;
}
ag.set_abonati(numar_abonati - 1);
numar_abonati--;
break;
}
}
cout << endl;
for ( i = 0 ; i < numar_abonati ; i++)
{
if(Abonat_Skype_Extern* n = dynamic_cast <Abonat_Skype_Extern*>(ag[i]))
cout << *n << endl;
else
if(Abonat_Skype_Romania* n = dynamic_cast <Abonat_Skype_Romania*>(ag[i]))
cout << *n << endl;
}
cout << endl;
cout << "Numar de obicte: ";
cout << Persoana::get_nr_obiecte() << endl;
for ( i = 0 ; i < numar_abonati ; i++)
{
delete ag[i];
}
cout << endl;
cout << "Numar de obicte: ";
cout << Persoana::get_nr_obiecte() << endl;
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
void modularExponent(int base, int exp, int mod){
int res=1;
base=base % mod;
while(exp){
if(exp%2==1){
res = (res*base)%mod;
}
exp=exp>>1;
base = (base*base)%mod;
}
cout<<res<<endl;
}
int main(){
int base,exp,mod;
cout<<"Enter base, exp and mod: ";
cin>>base>>exp>>mod;
modularExponent(base,exp,mod);
}
|
/* A module for low-level communication over the streaming virtio port.
*
* \copyright
* Copyright 2018 Red Hat Inc. All rights reserved.
*/
#ifndef SPICE_STREAMING_AGENT_STREAM_PORT_HPP
#define SPICE_STREAMING_AGENT_STREAM_PORT_HPP
#include <cstddef>
#include <string>
#include <mutex>
namespace spice {
namespace streaming_agent {
class StreamPort {
public:
StreamPort(const std::string &port_name);
~StreamPort();
void read(void *buf, size_t len);
void write(const void *buf, size_t len);
int fd;
std::mutex mutex;
};
void read_all(int fd, void *buf, size_t len);
void write_all(int fd, const void *buf, size_t len);
}} // namespace spice::streaming_agent
#endif // SPICE_STREAMING_AGENT_STREAM_PORT_HPP
|
//
// Created by goturak on 06/03/19.
//
#include "Addition.h"
int Addition::apply(int i1 , int i2){
return i1 + i2;
}
|
#ifndef __DACTPROPEDITOR_H
#define __DACTPROPEDITOR_H
#include "MAct.h"
#include "MProp.h"
#include "TPresenter.h"
#include "TViewCtrlPanel.h"
namespace wh{
namespace view{
//-----------------------------------------------------------------------------
/// Редактор для свойства действия
class DActPropEditor
: public view::DlgBaseOkCancel
, public T_View
{
public:
typedef MActProp T_Model;
DActPropEditor(wxWindow* parent = nullptr,
wxWindowID id = wxID_ANY,
const wxString& title = wxEmptyString,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxSize(400, 300),//wxDefaultSize,
long style = wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER,
const wxString& name = wxDialogNameStr);
virtual void SetModel(std::shared_ptr<IModel>& model)override;
virtual void UpdateModel()const override;
virtual int ShowModal() override;
private:
void OnChangeModel(const IModel* model, const T_Model::T_Data* data);
typedef view::TViewTable PropTable;
std::shared_ptr<MPropArray> mPropArray;
PropTable* mPropArrayView;
std::shared_ptr<T_Model> mModel; // std::shared_ptr<MActProp>
sig::scoped_connection mChangeConnection;
};
//-----------------------------------------------------------------------------
}//namespace view{
}//namespace wh{
#endif // __****_H
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
//
// Given a finite alphabet S, a binary code over this
// alphabet S is a
// function that maps each element of S to some (possibly
// empty) string over the alphabet {0,1}.
//
//
//
// An example of such a code for S={a,b,c,d} is the function
// f defined by
// f(a)=1, f(b)=1010, f(c)=01, f(d)=10101.
//
//
//
// Any binary code can be naturally extended to encode
// strings over the alphabet S
// simply by concatenating the codes of the string's letters,
// in order.
// For example, using the code mentioned above we can encode
// cac as f(cac)=01101.
//
//
//
// A code is called ambiguous if there are two different
// strings over S that have the same encoding.
// Obviously, in practice we want to avoid using an ambiguous
// code.
//
//
//
// A code is called really ambiguous if there are three
// different strings over S that have the same encoding.
// For example, the code from the above example is really
// ambiguous: the strings ba, acc, and d are all encoded to
// 10101.
//
//
//
// You will be given a vector <string> code containing the
// strings over {0,1} used to encode letters of some alphabet
// S.
// Your method should check whether this code is really
// ambiguous.
// If it is really ambiguous, find a shortest string over
// {0,1} that is an encoding of (at least) three different
// strings over S, and return its length.
// If the given code is not really ambiguous, return -1.
//
//
// DEFINITION
// Class:BinaryCodes
// Method:ambiguous
// Parameters:vector <string>
// Returns:int
// Method signature:int ambiguous(vector <string> code)
//
//
// NOTES
// -Your method does not need to know the actual elements of
// S, and the size of S is obviously equal to the number of
// elements in code.
//
//
// CONSTRAINTS
// -code will contain between 2 and 30 elements, inclusive.
// -Each element of code will contain between 0 and 50
// characters, inclusive.
// -Each element of code will only contain the characters '0'
// (zero) and '1' (one).
//
//
// EXAMPLES
//
// 0)
// {"1","1010","01","10101"}
//
// Returns: 5
//
// This is the example from the problem statement, and the
// string 10101 is the shortest string that can be decoded in
// three different ways.
//
// 1)
// {"0","1"}
//
// Returns: -1
//
// This code is obviously not ambiguous.
//
//
// 2)
// {"0","11","11","11"}
//
// Returns: 2
//
// This is clearly a really ambiguous code, as there are
// three different one letter strings over
// S that are encoded to 11.
//
//
// 3)
// {"0000","001","01001","01010","01011"}
//
// Returns: -1
//
// This code is a prefix code, i.e., no code word is a prefix
// of another code word. If a code has this
// property, it is guaranteed that it is not ambiguous, but
// the other direction is not true.
//
//
// 4)
// {"1","10","00"}
//
// Returns: -1
//
// This is not a prefix code, but it can easily be shown that
// this code is not ambiguous.
//
//
// 5)
// {"","01101001001","111101011"}
//
// Returns: 0
//
// Having an empty code word is a great way how to design a
// really ambiguous code.
//
//
// 6)
// {"00011011","000110","11","0001","1011","00","011011"}
//
// Returns: 8
//
// The shortest proof that this code is really ambiguous is
// 00011011. Note that this string can in fact be decoded in
// four different ways.
//
// END CUT HERE
#line 143 "BinaryCodes.cpp"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
class BinaryCodes
{
public:
int ambiguous(vector <string> code)
{
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"1","1010","01","10101"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 5; verify_case(0, Arg1, ambiguous(Arg0)); }
void test_case_1() { string Arr0[] = {"0","1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = -1; verify_case(1, Arg1, ambiguous(Arg0)); }
void test_case_2() { string Arr0[] = {"0","11","11","11"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(2, Arg1, ambiguous(Arg0)); }
void test_case_3() { string Arr0[] = {"0000","001","01001","01010","01011"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = -1; verify_case(3, Arg1, ambiguous(Arg0)); }
void test_case_4() { string Arr0[] = {"1","10","00"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = -1; verify_case(4, Arg1, ambiguous(Arg0)); }
void test_case_5() { string Arr0[] = {"","01101001001","111101011"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; verify_case(5, Arg1, ambiguous(Arg0)); }
void test_case_6() { string Arr0[] = {"00011011","000110","11","0001","1011","00","011011"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 8; verify_case(6, Arg1, ambiguous(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
BinaryCodes ___test;
___test.run_test(-1);
}
// END CUT HERE
|
/*
Name: ·´×ªÁ´±í
Copyright:
Author: Hill Bamboo
Date: 2019/8/30 12:11:53
Description:
*/
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
};
ListNode* reverse1(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode* pre = head;
ListNode* cur = head->next;
ListNode* tmp = head->next->next;
while (cur) {
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
head->next = nullptr;
return pre;
}
ListNode* reverse2(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
stack<ListNode*> stk;
while (head) {
stk.push(head);
head = head->next;
}
ListNode* ret = stk.top(); stk.pop();
ListNode* cur = ret;
while (!stk.empty()) {
cur->next = stk.top(); stk.pop();
cur = cur->next;
}
cur->next = nullptr;
return ret;
}
int main() {
return 0;
}
|
#include "Config.h"
Config::Config()
:
WIDTH(640),
HEIGHT(640),
TITLE("Fractal Renderer"),
VERTEX_START_STRING("$vertex"),
FRAGMENT_START_STRING("$fragment"),
BG_COLOR({ 0, 0, 0 }),
SPEED(5),
VIEW_LEFT(-320.f),
VIEW_RIGHT(320.f),
VIEW_BOTTOM(-320.f),
VIEW_TOP(320.f),
CELL_WIDTH(160),
AXIS_SIZE({ 5.f, 5.f }),
SENSITIVITY(0.01),
CELL_SIZE(160)
{}
Config& c() {
static Config configData;
return configData;
}
|
// Created on: 2005-03-15
// Created by: Peter KURNEV
// Copyright (c) 2005-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 _Standard_MMgrOpt_HeaderFile
#define _Standard_MMgrOpt_HeaderFile
#include <Standard_MMgrRoot.hxx>
#include <Standard_Mutex.hxx>
/**
* @brief Open CASCADE memory manager optimized for speed.
*
* The behaviour is different for memory blocks of different sizes,
* according to specified options provided to constructor:
*
* - Small blocks with size less than or equal to aCellSize are allocated
* in big pools of memory. The parameter aNbPages specifies size of
* these pools in pages (operating system-dependent).
* When freed, small block is not returned to the system but added
* into free blocks list and reused when block of the same size is
* requested.
*
* - Medium size blocks with size less than aThreshold are allocated
* using malloc() or calloc() function but not returned to the system
* when method Free() is called; instead they are put into free list
* and reused when block of the same size is requested.
* Blocks of medium size stored in free lists can be released to the
* system (by free()) by calling method Purge().
*
* - Large blocks with size greater than or equal to aThreshold are allocated
* and freed directly: either using malloc()/calloc() and free(), or using
* memory mapped files (if option aMMap is True)
*
* Thus the optimization of memory allocation/deallocation is reached
* for small and medium size blocks using free lists method;
* note that space allocated for small blocks cannot be (currently) released
* to the system while space for medium size blocks can be released by method Purge().
*
* Note that destructor of that class frees all free lists and memory pools
* allocated for small blocks.
*
* Note that size of memory blocks allocated by this memory manager is always
* rounded up to 16 bytes. In addition, 8 bytes are added at the beginning
* of the memory block to hold auxiliary information (size of the block when
* in use, or pointer to the next free block when in free list).
* This the expense of speed optimization. At the same time, allocating small
* blocks is usually less costly than directly by malloc since allocation is made
* once (when allocating a pool) and overheads induced by malloc are minimized.
*/
class Standard_MMgrOpt : public Standard_MMgrRoot
{
public:
//! Constructor. If aClear is True, the allocated emmory will be
//! nullified. For description of other parameters, see description
//! of the class above.
Standard_EXPORT Standard_MMgrOpt
(const Standard_Boolean aClear = Standard_True,
const Standard_Boolean aMMap = Standard_True,
const Standard_Size aCellSize = 200,
const Standard_Integer aNbPages = 10000,
const Standard_Size aThreshold = 40000);
//! Frees all free lists and pools allocated for small blocks
Standard_EXPORT virtual ~Standard_MMgrOpt();
//! Allocate aSize bytes; see class description above
Standard_EXPORT virtual Standard_Address Allocate(const Standard_Size aSize);
//! Reallocate previously allocated aPtr to a new size; new address is returned.
//! In case that aPtr is null, the function behaves exactly as Allocate.
Standard_EXPORT virtual Standard_Address Reallocate (Standard_Address thePtr,
const Standard_Size theSize);
//! Free previously allocated block.
//! Note that block can not all blocks are released to the OS by this
//! method (see class description)
Standard_EXPORT virtual void Free (Standard_Address thePtr);
//! Release medium-sized blocks of memory in free lists to the system.
//! Returns number of actually freed blocks
Standard_EXPORT virtual Standard_Integer Purge(Standard_Boolean isDestroyed);
//! Declaration of a type pointer to the callback function that should accept the following arguments:
//! @param theIsAlloc true if the data is allocated, false if it is freed
//! @param theStorage address of the allocated/freed block
//! @param theRoundSize the real rounded size of the block
//! @param theSize the size of the block that was requested by application (this value is correct only if theIsAlloc is true)
typedef void (*TPCallBackFunc)(const Standard_Boolean theIsAlloc,
const Standard_Address theStorage,
const Standard_Size theRoundSize,
const Standard_Size theSize);
//! Set the callback function. You may pass 0 there to turn off the callback.
//! The callback function, if set, will be automatically called from within
//! Allocate and Free methods.
Standard_EXPORT static void SetCallBackFunction(TPCallBackFunc pFunc);
protected:
//! Internal - initialization of buffers
Standard_EXPORT void Initialize();
//! Internal - allocation of memory using either malloc or memory mapped files.
//! The size of the actually allocated block may be greater than requested one
//! when memory mapping is used, since it is aligned to page size
Standard_Size* AllocMemory (Standard_Size &aSize);
//! Internal - deallocation of memory taken by AllocMemory
void FreeMemory (Standard_Address aPtr, const Standard_Size aSize);
//! Internal - free memory pools allocated for small size blocks
void FreePools();
protected:
Standard_Boolean myClear; //!< option to clear allocated memory
Standard_Size myFreeListMax; //!< last allocated index in the free blocks list
Standard_Size ** myFreeList; //!< free blocks list
Standard_Size myCellSize; //!< small blocks size
Standard_Integer myNbPages; //!< size (pages) for small block memory pools
Standard_Size myPageSize; //!< system-dependent memory page size
Standard_Size * myAllocList; //!< list of memory pools for small blocks
Standard_Size * myNextAddr; //!< next free address in the active memory pool
Standard_Size * myEndBlock; //!< end of the active memory pool
Standard_Integer myMMap; //!< non-null if using memory mapped files for allocation of large blocks
Standard_Size myThreshold; //!< large block size
Standard_Mutex myMutex; //!< Mutex to protect free lists data
Standard_Mutex myMutexPools; //!< Mutex to protect small block pools data
};
#endif
|
#include "Arduino.h"
#include "HCSR04.h"
HCSR04::HCSR04(int echo, int trig) {
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
echopin = echo;
trigpin = trig;
count = 0;
duration = 0;
distance = 0;
}
double HCSR04::getdist() {
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
if (duration > 0) {
count++;
if (count == NUM) {
count = 0;
}
duration /= 2;
distance = duration * 340 * 100 / 100000;
if(distance <= 30000){
return distance;
}
}
}
double HCSR04::getdist(double temp) {
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
if (duration > 0) {
count++;
if (count == NUM) {
count = 0;
}
duration /= 2;
distance = duration * (331.5 + 0.6 * temp) * 100 / 100000;
return distance;
}
}
|
/**********************************************************************
*Project : EngineTask
*
*Author : Jorge Cásedas
*
*Starting date : 24/06/2020
*
*Ending date : 03/07/2020
*
*Purpose : Creating a 3D engine that can be used later on for developing a playable demo, with the engine as static library
*
**********************************************************************/
#include "Transform.hpp"
namespace engine
{
Transform::Transform()
{
lastXPos = 0;
lastYPos = 0;
lastZPos = 0;
xPos = 0;
yPos = 0;
zPos = 0;
xSize = 1;
ySize = 1;
zSize = 1;
}
void Transform::SetScale(float x, float y, float z)
{
xSize = x;
ySize = y;
zSize = z;
}
void Transform::GetScale(float& x, float& y, float& z)
{
x = xSize;
y = ySize;
z = zSize;
}
void Transform::SetPosition(float x, float y, float z)
{
ResetLastPos();
xPos = x;
yPos = y;
zPos = z;
}
void Transform::GetPosition(float& x, float& y, float& z)
{
x = xPos;
y = yPos;
z = zPos;
}
void Transform::Translate(float x, float y, float z)
{
//SetPosition(xPos+x, yPos+y, zPos+z);
xPos += x;
yPos += y;
zPos += z;
}
void Transform::GetLastTransformation(float& x, float& y, float& z)
{
x = xPos - lastXPos;
y = yPos - lastYPos;
z = zPos - lastZPos;
ResetLastPos();
}
void Transform::ResetLastPos()
{
lastXPos = xPos;
lastYPos = yPos;
lastZPos = zPos;
}
}
|
#pragma once
#include <frc/commands/Subsystem.h>
class ExampleSubsystem : public frc::Subsystem
{
public:
ExampleSubsystem();
void InitDefaultCommand() override;
};
|
// std headers
#include <iostream>
// arrow headers
#include <arrow/api.h>
using namespace arrow;
struct data_row_t {
data_row_t(int64_t id_, double cost_, std::vector<double> v)
: id(id_), cost(cost_), cost_components(std::move(v))
{}
data_row_t(data_row_t const& other) :
id(other.id), cost(other.cost), cost_components(other.cost_components)
{}
data_row_t(data_row_t&& other) :
id(other.id), cost(other.cost), cost_components(std::move(other.cost_components))
{}
int64_t id;
double cost;
std::vector<double> cost_components;
};
int main() {
std::vector<data_row_t> rows;
std::cout << "111" << std::endl;
for (int64_t i=0; i<100; i++) {
std::vector<double> tmp {1.5, 2.5, 3.5};
rows.emplace_back(
i, double(i), tmp
);
}
std::cout << "222" << std::endl;
using arrow::DoubleBuilder;
using arrow::Int64Builder;
using arrow::ListBuilder;
arrow::MemoryPool *pool = arrow::default_memory_pool();
Int64Builder id_builder(pool);
DoubleBuilder cost_builder(pool);
std::unique_ptr<DoubleBuilder> components_values_builder(new DoubleBuilder(pool));
ListBuilder components_builder(pool, std::move(components_values_builder));
std::cout << "333" << std::endl;
for (auto const& row : rows) {
id_builder.Append(row.id);
cost_builder.Append(row.cost);
components_builder.Append();
DoubleBuilder* bld = static_cast<DoubleBuilder*>(components_builder.value_builder());
bld->Append(
row.cost_components.data(), row.cost_components.size(),
nullptr);
}
std::cout << "444" << std::endl;
std::shared_ptr<arrow::Array> id_array;
id_builder.Finish(&id_array);
std::shared_ptr<arrow::Array> cost_array;
cost_builder.Finish(&cost_array);
std::shared_ptr<arrow::Array> cost_components_array;
components_builder.Finish(&cost_components_array);
std::vector<std::shared_ptr<arrow::Field>> schema_vector = {
arrow::field("id", arrow::int64()),
arrow::field("cost", arrow::float64()),
arrow::field("cost_components", arrow::list(arrow::float64()))
};
auto schema = std::make_shared<arrow::Schema>(schema_vector);
std::shared_ptr<arrow::Table> table = arrow::Table::Make(schema, {id_array, cost_array, cost_components_array});
arrow::PrettyPrint(*schema, {5}, &(std::cout));
std::cout << std::endl;
arrow::PrettyPrint(*id_array, {2}, &(std::cout));
std::cout << std::endl;
arrow::PrettyPrint(*cost_array, {2}, &(std::cout));
std::cout << std::endl;
arrow::PrettyPrint(*cost_components_array, {2}, &std::cout);
std::cout << std::endl;
}
|
//
// MyBizierWarp.h
// ParticleMotion
//
// Created by james KONG on 13/8/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#ifndef ParticleMotion_MyBizierWarp_h
#define ParticleMotion_MyBizierWarp_h
#include "ofxBezierWarp.h"
#include "ofxGLWarper.h"
#include "ofxSimpleGuiToo.h"
#include "ofxTextInputField.h"
#include "ofxProjectorBlend.h"
#define PIXEL_OVERLAP 40
#define PROJECTOR_COUNT N_SCREEN
#define PROJECTOR_WIDTH WIDTH
#define PROJECTOR_HEIGHT HEIGHT
struct Selection
{
bool corners[4];
bool anchors[8];
bool *grids;
};
class MyBizierWarp
{
public:
void setup()
{
// offset[1][0].set(1,1);
// offset[1][1].set(1,1);
// offset[1][2].set(1,1);
// offset[1][3].set(1,1);
for(int i= 0 ; i < N_SCREEN ; i++)
{
offset[i][0].set(i,1);
offset[i][1].set(i,1);
offset[i][2].set(i,1);
offset[i][3].set(i,1);
bz[i].setup(10,N_SCREEN,WIDTH*N_SCREEN,HEIGHT,"preset"+ofToString(i)+".xml");
//bz[i].setup(16,"preset"+ofToString(i)+".bin");
//bz[i].recall();
bz[i].inactive();
// warper[i].setup(); //initializates ofxGLWarper
// warper[i].deactivate();// this allows ofxGLWarper to automatically listen to the mouse and keyboard
gui.addPage("Screen"+ofToString(i));
gui.addToggle("Screen"+ofToString(i)+"Active",bz[i].isActive);
gui.addToggle("CORNER1", selection[i].corners[0]);
gui.addToggle("CORNER2", selection[i].corners[1]);
gui.addToggle("CORNER3", selection[i].corners[2]);
gui.addToggle("CORNER4", selection[i].corners[3]);
gui.addToggle("ANCHOR1", selection[i].anchors[0]);
gui.addToggle("ANCHOR2", selection[i].anchors[1]);
gui.addToggle("ANCHOR3", selection[i].anchors[2]);
gui.addToggle("ANCHOR4", selection[i].anchors[3]);
gui.addToggle("ANCHOR5", selection[i].anchors[4]);
gui.addToggle("ANCHOR6", selection[i].anchors[5]);
gui.addToggle("ANCHOR7", selection[i].anchors[6]);
gui.addToggle("ANCHOR8", selection[i].anchors[7]);
gui.addPage("Screen"+ofToString(i)+"Grid");
selection[i].grids = new bool [(bz[i].gridRes+1)*(bz[i].gridRes+1)];
for(int y = 0 ; y <=bz[i].gridRes ;y++)
{
for(int x = 0 ; x <=bz[i].gridRes ;x++)
{
selection[i].grids[x+(y*(bz[i].gridRes+1))] = false;
gui.addToggle("GRID"+ofToString(x)+"-"+ofToString(y), selection[i].grids[x+(y*(bz[i].gridRes+1))]);//.setNewColumn((x==0 && y!=0));
}
}
// gui.currentPage().setXMLName("Warpping"+ofToString(i)+".xml");
gui.addPage("Screen"+ofToString(i)+"Control");
gui.addButton("Relaod", bReload[i]);
gui.addButton("Save", bSave[i]);
gui.addButton("UP", bPointUP).setNewColumn(true);
gui.addButton("DOWN", bPointDOWN);
gui.addButton("LEFT", bPointLEFT);
gui.addButton("RIGHT", bPointRIGHT);
}
fbo.allocate(WIDTH, HEIGHT);
gui.loadFromXML();
for(int i= 0 ; i < N_SCREEN ; i++)
{
bz[i].recall();
}
// blender.setShaderLocation(ofToDataPath("shaders/SmoothEdgeBlend"));
blender.setup(WIDTH, HEIGHT, N_SCREEN, PIXEL_OVERLAP);
blender.gamma = .5;
blender.blendPower = 1;
blender.luminance = 0;
blender.addGuiPage();
gui.loadFromXML();
// ofShader shader;
// shader.load("shaders/SmoothEdgeBlend");
}
void update()
{
// for(int i = 0 ; i< N_SCREEN ;i++)
// {
// bz[i].recall();
// }
for(int i= 0 ; i < N_SCREEN ; i++)
{
if(bReload[i])
{
bz[i].recall();
}
else if(bSave[i])
{
bz[i].save();
}
}
//ofLog(OF_LOG_VERBOSE," bPointUP %i ",bPointUP);
float diff = ofGetElapsedTimef()-elapsed;
if (bPointUP)
{
modifyPoint(ofPoint(0,-diff));
}
else if (bPointDOWN)
{
modifyPoint(ofPoint(0,diff));
}
else if (bPointLEFT)
{
modifyPoint(ofPoint(-diff,0));
}
else if (bPointRIGHT)
{
modifyPoint(ofPoint(diff,0));
}
}
void modifyPoint(ofPoint p )
{
for(int i= 0 ; i < N_SCREEN ; i++)
{
if(bz[i].isActive)
{
if(selection[i].corners[0])bz[i].corners[0]+=p;
if(selection[i].corners[1])bz[i].corners[1]+=p;
if(selection[i].corners[2])bz[i].corners[2]+=p;
if(selection[i].corners[3])bz[i].corners[3]+=p;
if(selection[i].anchors[0])bz[i].anchors[0]+=p;
if(selection[i].anchors[1])bz[i].anchors[1]+=p;
if(selection[i].anchors[2])bz[i].anchors[2]+=p;
if(selection[i].anchors[3])bz[i].anchors[3]+=p;
if(selection[i].anchors[4])bz[i].anchors[4]+=p;
if(selection[i].anchors[5])bz[i].anchors[5]+=p;
if(selection[i].anchors[6])bz[i].anchors[6]+=p;
if(selection[i].anchors[7])bz[i].anchors[7]+=p;
for(int y = 0 ; y <=bz[i].gridRes ;y++)
{
for(int x = 0 ; x <=bz[i].gridRes ;x++)
{
if(selection[i].grids[x+(y*(bz[i].gridRes+1))])bz[i].gridPoint[x][y]+=p;
}
}
}
}
}
void begin()
{
fbo.begin();
// blender.begin();
//
ofSetColor(100, 100, 100);
ofRect(0, 0, blender.getCanvasWidth(), blender.getCanvasHeight());
}
void end()
{
fbo.end();
// blender.end();
}
void draw()
{
blender.begin();
for(int i= 0 ; i < N_SCREEN ; i++)
{
bz[i].draw(fbo.getTextureReference(),offset[i], N_SCREEN);
}
blender.end();
blender.draw();
if(gui.isOn())
{
int size = 30;
ofPushStyle();
ofNoFill();
ofSetColor(100, 255, 100);
for(int i = 0 ; i < N_SCREEN ; i++)
{
if(bz[i].isActive)
{
if(selection[i].corners[0])ofCircle(bz[i].corners[0],size);
if(selection[i].corners[1])ofCircle(bz[i].corners[1],size);
if(selection[i].corners[2])ofCircle(bz[i].corners[2],size);
if(selection[i].corners[3])ofCircle(bz[i].corners[3],size);
if(selection[i].anchors[0])ofCircle(bz[i].anchors[0],size);
if(selection[i].anchors[1])ofCircle(bz[i].anchors[1],size);
if(selection[i].anchors[2])ofCircle(bz[i].anchors[2],size);
if(selection[i].anchors[3])ofCircle(bz[i].anchors[3],size);
if(selection[i].anchors[4])ofCircle(bz[i].anchors[4],size);
if(selection[i].anchors[5])ofCircle(bz[i].anchors[5],size);
if(selection[i].anchors[6])ofCircle(bz[i].anchors[6],size);
if(selection[i].anchors[7])ofCircle(bz[i].anchors[7],size);
for(int y = 0 ; y <=bz[i].gridRes ;y++)
{
for(int x = 0 ; x <=bz[i].gridRes ;x++)
{
if(selection[i].grids[x+((y*(bz[i].gridRes+1)))]){
ofPoint p = bz[i].drawDrid(x,y);
//textfield.text = ofToString(p.x)+"\n"+ofToString(p.y);
//textfield.draw(p.x,p.y);
}
}
}
}
}
ofPopStyle();
}
}
//--------------------------------------------------------------
void keyPressed(int key){
for(int i= 0 ; i < N_SCREEN ; i++)
{
bz[i].keyPressed(key);
}
switch(key)
{
case 'A':
if(!bPointLEFT){
bPointLEFT = true;
elapsed = ofGetElapsedTimef();
}
break;
case 'D':
if(!bPointRIGHT){
bPointRIGHT = true;
elapsed = ofGetElapsedTimef();
} break;
case 'S':
if(!bPointDOWN){
bPointDOWN = true;
elapsed = ofGetElapsedTimef();
} break;
case 'W':
if(!bPointUP){
bPointUP = true;
elapsed = ofGetElapsedTimef();
} break;
}
for(int i = 0 ; i < N_SCREEN ; i++)
{
if(bz[i].isActive)bz[i].active();
else bz[i].inactive();
}
}
//--------------------------------------------------------------
void keyReleased(int key){
switch(key)
{
case 'A':
{
bPointLEFT = false;
}
break;
case 'D':
{
bPointRIGHT = false;
} break;
case 'S':
{
bPointDOWN = false;
} break;
case 'W':
{
bPointUP = false;
} break;
// case '0':
// // warper[0].deactivate();
// bz[0].inactive();
// if(N_SCREEN>1)
// {
// bz[1].inactive();
// // warper[1].deactivate();
// }
//
// //ofHideCursor();
// break;
// case '1':
// bz[0].active();
// // warper[0].activate();
// if(N_SCREEN>1)
// {
// bz[1].inactive();
// // warper[1].deactivate();
// }
// //ofShowCursor();
// break;
// case '2':
// bz[0].inactive();
// // warper[0].deactivate();
// if(N_SCREEN>1)
// {
// bz[1].active();
// // warper[1].activate();
// }
// //ofShowCursor();
// break;
case 'd':
for(int i = 0 ; i < N_SCREEN ; i++)
{
bz[i].defaults(i);
}
break;
}
for(int i = 0 ; i < N_SCREEN ; i++)
{
if(bz[i].isActive)bz[i].active();
else bz[i].inactive();
}
}
//--------------------------------------------------------------
void mouseDragged(int x, int y, int button){
for(int i= 0 ; i < N_SCREEN ; i++)
{
bz[i].mouseDragged(x, y);
}
}
//--------------------------------------------------------------
void mousePressed(int x, int y, int button){
for(int i= 0 ; i < N_SCREEN ; i++)
{
bz[i].mousePressed(x, y);
}
elapsed = ofGetElapsedTimef();
}
//--------------------------------------------------------------
void mouseReleased(int x, int y, int button){
// for(int i= 0 ; i < N_SCREEN ; i++)
// {
// bz[i].mouseReleased(x, y);
// }
for(int i = 0 ; i < N_SCREEN ; i++)
{
if(bz[i].isActive)bz[i].active();
else bz[i].inactive();
}
elapsed = ofGetElapsedTimef();
}
ofxBezierWarp bz[N_SCREEN];
ofxProjectorBlend blender;
//ofxGLWarper warper[N_SCREEN];
ofFbo fbo;//[N_SCREEN];
ofPoint offset[N_SCREEN][4];
// ofPoint offset2[4];
bool bReload[N_SCREEN],bSave[N_SCREEN];
int choice_out[N_SCREEN];
Selection selection[N_SCREEN];
bool bPointUP,bPointDOWN,bPointLEFT,bPointRIGHT;
float elapsed;
ofxTextInputField textfield;
};
#endif
|
#ifndef __sudoku__LedSolver__
#define __sudoku__LedSolver__
#include "Headers.h"
//using namespace cv::ml;
class LedSolver {
public:
LedSolver();
~LedSolver();
//void init(const char* file);
void init();
bool process(Mat& led_roi, Rect& bound_all_rect);
int getResult(int index);
void setParam(int index, int value);
bool confirmLed();
enum LedParam{
RED_THRESHOLD,
GRAY_THRESHOLD,
BOUND_AREA_MIN,
BOUND_AREA_MAX,
HW_RATIO_MIN,
HW_RATIO_MAX,
HW_RATIO_FOR_DIGIT_ONE,
ROTATION_DEGREE,
PARAM_SIZE
};
private:
//Ptr<SVM> svm;
Mat kernel;
//HOGDescriptor* hog;
int results[5];
int param[PARAM_SIZE];
void getRed(Mat& led_roi, Mat& led_roi_binary);
//int predictSVM(Mat& roi);
int predictCross(Mat& roi);
int scanSegmentX(Mat& roi, int line_x, int y_begin, int y_end);
int scanSegmentY(Mat& roi, int line_y, int x_begin, int x_end);
};
#endif /* ifndef __sudoku__LedSolver__ */
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
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))
#define yn YN
using namespace std;
const int N = 422222;
struct Tp {
int t, x, y;
} a[N];
int xx[N], xn = 0;
int l[N], r[N], ls[N], rs[N], kw[N];
set<int> S[N], S2[N];
void add_point(int y, int x) {
int yy = y;
while (y) {
S[y].insert(x);
y &= y - 1;
}
y = yy;
while (y <= xn) {
S2[y].insert(x);
y = (y | (y - 1)) + 1;
}
}
int find_min_greater_up(int y, int x) {
int ans = 2e9;
while (y <= xn) {
set<int>::const_iterator i = S[y].upper_bound(x);
if (i != S[y].end() && ans > *i) ans = *i;
y = (y | (y - 1)) + 1;
}
if (ans == 2e9) return 0;
return ans;
}
int find_max_less_up(int y, int x) {
int ans = -2e9;
while (y <= xn) {
set<int>::const_iterator i = S[y].lower_bound(x);
if (i != S[y].begin()) {
--i;
if (ans < *i) ans = *i;
}
y = (y | (y - 1)) + 1;
}
if (ans == -2e9) return 0;
return ans;
}
int find_min_greater_down(int y, int x) {
int ans = 2e9;
while (y) {
set<int>::const_iterator i = S2[y].upper_bound(x);
if (i != S2[y].end() && ans > *i) ans = *i;
y &= y - 1;
}
if (ans == 2e9) return 0;
return ans;
}
int find_max_less_down(int y, int x) {
int ans = -2e9;
while (y) {
set<int>::const_iterator i = S2[y].lower_bound(x);
if (i != S2[y].begin()) {
--i;
if (ans < *i) ans = *i;
}
y &= y - 1;
}
if (ans == -2e9) return 0;
return ans;
}
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d%d", &a[i].t, &a[i].x);
xx[xn++] = a[i].x;
if (a[i].t != 1) {
scanf("%d", &a[i].y);
xx[xn++]= a[i].y;
}
}
sort(xx, xx + xn); xn = unique(xx, xx + xn) - xx;
for (int i = 0; i < n; ++i) {
if (a[i].t == 0) { // add
int k = lower_bound(xx, xx + xn, a[i].x) - xx + 1;
int w = lower_bound(xx, xx + xn, a[i].y) - xx + 1;
kw[k] = w;
int father = find_min_greater_up(w, k);
if (father > 1e9 || l[father] > k || r[father] < k) {
father = find_max_less_up(w, k);
}
if (father < -1e9 || l[father] > k || r[father] < k) {
l[k] = 1, r[k] = xn;
} else {
if (k < father)
l[k] = l[father], r[k] = father - 1;
else
l[k] = father + 1, r[k] = r[father];
}
add_point(k, w);
}
}
return 0;
}
|
// Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef SHOOTERSTARTER_ShooterStarterPlayerController_generated_h
#error "ShooterStarterPlayerController.generated.h already included, missing '#pragma once' in ShooterStarterPlayerController.h"
#endif
#define SHOOTERSTARTER_ShooterStarterPlayerController_generated_h
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_SPARSE_DATA
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_RPC_WRAPPERS
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_RPC_WRAPPERS_NO_PURE_DECLS
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesAShooterStarterPlayerController(); \
friend struct Z_Construct_UClass_AShooterStarterPlayerController_Statics; \
public: \
DECLARE_CLASS(AShooterStarterPlayerController, APlayerController, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/ShooterStarter"), NO_API) \
DECLARE_SERIALIZER(AShooterStarterPlayerController)
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_INCLASS \
private: \
static void StaticRegisterNativesAShooterStarterPlayerController(); \
friend struct Z_Construct_UClass_AShooterStarterPlayerController_Statics; \
public: \
DECLARE_CLASS(AShooterStarterPlayerController, APlayerController, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/ShooterStarter"), NO_API) \
DECLARE_SERIALIZER(AShooterStarterPlayerController)
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API AShooterStarterPlayerController(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AShooterStarterPlayerController) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AShooterStarterPlayerController); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AShooterStarterPlayerController); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API AShooterStarterPlayerController(AShooterStarterPlayerController&&); \
NO_API AShooterStarterPlayerController(const AShooterStarterPlayerController&); \
public:
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API AShooterStarterPlayerController(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API AShooterStarterPlayerController(AShooterStarterPlayerController&&); \
NO_API AShooterStarterPlayerController(const AShooterStarterPlayerController&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AShooterStarterPlayerController); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AShooterStarterPlayerController); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AShooterStarterPlayerController)
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_PRIVATE_PROPERTY_OFFSET \
FORCEINLINE static uint32 __PPO__LoseScreenClass() { return STRUCT_OFFSET(AShooterStarterPlayerController, LoseScreenClass); } \
FORCEINLINE static uint32 __PPO__WinScreenClass() { return STRUCT_OFFSET(AShooterStarterPlayerController, WinScreenClass); } \
FORCEINLINE static uint32 __PPO__HUDClass() { return STRUCT_OFFSET(AShooterStarterPlayerController, HUDClass); } \
FORCEINLINE static uint32 __PPO__RestartDelay() { return STRUCT_OFFSET(AShooterStarterPlayerController, RestartDelay); } \
FORCEINLINE static uint32 __PPO__HUDScreen() { return STRUCT_OFFSET(AShooterStarterPlayerController, HUDScreen); }
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_12_PROLOG
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_PRIVATE_PROPERTY_OFFSET \
ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_SPARSE_DATA \
ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_RPC_WRAPPERS \
ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_INCLASS \
ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_PRIVATE_PROPERTY_OFFSET \
ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_SPARSE_DATA \
ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_RPC_WRAPPERS_NO_PURE_DECLS \
ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_INCLASS_NO_PURE_DECLS \
ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h_15_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> SHOOTERSTARTER_API UClass* StaticClass<class AShooterStarterPlayerController>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID ShooterStarter_Source_ShooterStarter_ShooterStarterPlayerController_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.