text
stringlengths 8
6.88M
|
|---|
#include "loginwidget.h"
#include "ui_loginwidget.h"
#include "ui/Callbacks/Login.h"
#include "ui/UserData/UserData.h"
LoginWidget::LoginWidget(QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::LoginWidget) {
ui->setupUi(this);
this->resize(810, 550);
this->setMinimumSize(810, 550);
this->setMaximumSize(810, 550);
this->setWindowTitle("InCorp - messenger");
}
LoginWidget::~LoginWidget() {
delete ui;
}
void LoginWidget::on_loginButton_clicked() {
login(ui->loginInput->text(),ui->passwordInput->text());
}
void LoginWidget::login(const QString &login, const QString &password) {
const std::string log = login.toStdString();
const std::string pass = password.toStdString();
if ((log != "") && (pass != "")) {
auto authInfo = UserInfo(log, pass);
auto client = Controller::getInstance();
auto callback = std::make_shared<LoginCallback>(shared_from_this());
auto userData = UserData::getInstance();
client->authorization(authInfo, userData->userId, callback);
ui->loginInput->clear();
ui->passwordInput->clear();
ui->SignInLabel->clear();
}
}
void LoginWidget::showMainWidget() {
emit openMainWidget();
this->close();
}
|
// **************************************
// File: glenv.h
// Copyright: Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved.
// Website: http://www.nuiengine.com
// Description: This code is part of NUI Engine (NUI Graphics Lib)
// Comments:
// Rev: 2
// Created: 2017/4/11
// Last edit: 2017/4/28
// Author: Chen Zhi
// E-mail: cz_666@qq.com
// License: APACHE V2.0 (see license file)
// ***************************************
#ifndef GLENV_H
#define GLENV_H
#include <GL/gl.h>
#include <GL/glu.h>
class NUI_API CGLEvn
{
public:
CGLEvn();
~CGLEvn();
//释放
void glenvRelease();
//初始化环境
bool glenvInit(HDC hdc, int x, int y, int t, int b, bool b_mem = FALSE);
//设为当前环境
bool glenvActive();
//上屏
void SwapBuffers();
HGLRC m_hrc;
HDC m_hdc;
RECT m_rectClient;
kn_bool m_b_init;
};
#endif //GLENV_H
|
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_map>
#include <string>
#include <set>
#include <stack>
#include <cstdio>
#include <cstring>
#include <climits>
using namespace std;
struct Node {
int id, v, t;
Node(){}
Node(int i, int v, int t):id(i), v(v), t(t){}
bool operator< (const Node& b) const {
if (t + v == b.t + b.v) {
if (v == b.v) {
return id < b.id;
}
else return v > b.v;
}
else return t + v > b.t + b.v;
}
};
int main() {
int N, L, H;
scanf("%d %d %d", &N, &L, &H);
int id, v, t;
vector<Node> sage, noble, fool, small;
for (int i = 0; i < N; i++) {
scanf("%d %d %d", &id, &v, &t);
if (t >= L && v >= L) {
if (v >= H && t >= H) {
sage.push_back(Node(id, v, t));
}
else if (t < H && v >= H) {
noble.push_back(Node(id, v, t));
}
else if (t < H && v < H && t <= v) {
fool.push_back(Node(id, v, t));
}
else {
small.push_back(Node(id, v, t));
}
}
}
sort(sage.begin(), sage.end());
sort(noble.begin(), noble.end());
sort(fool.begin(), fool.end());
sort(small.begin(), small.end());
printf("%d\n", sage.size() + noble.size() + fool.size() + small.size());
for (auto item : sage) printf("%08d %d %d\n", item.id, item.v, item.t);
for (auto item : noble) printf("%08d %d %d\n", item.id, item.v, item.t);
for (auto item : fool) printf("%08d %d %d\n", item.id, item.v, item.t);
for (auto item : small) printf("%08d %d %d\n", item.id, item.v, item.t);
return 0;
}
|
#ifndef __PAGEUSERLIST_H
#define __PAGEUSERLIST_H
#include "CtrlWindowBase.h"
//#include "MUser2.h"
#include "VUserCtrlPanel.h"
namespace wh{
//---------------------------------------------------------------------------
class ModelPageUserList : public IModelWindow
{
public:
ModelPageUserList(const std::shared_ptr<rec::PageUser>& usr)
{
}
virtual void UpdateTitle()override
{
sigUpdateTitle("Пользователи", ResMgr::GetInstance()->m_ico_user24);
}
virtual void Load(const boost::property_tree::wptree& page_val)override
{
}
virtual void Save(boost::property_tree::wptree& page_val)override
{
using ptree = boost::property_tree::wptree;
ptree content;
page_val.push_back(std::make_pair(L"CtrlPageUserList", content));
}
std::shared_ptr<MUserArray> mUserList = std::make_shared<MUserArray>();
wh::SptrIModel GetWhModel()const
{
return std::dynamic_pointer_cast<IModel>(mUserList);
}
};
//---------------------------------------------------------------------------
class ViewPageUserList : public IViewWindow
{
view::VUserCtrlPanel* mPanel;
public:
ViewPageUserList(std::shared_ptr<IViewNotebook> parent)
{
mPanel = new view::VUserCtrlPanel(parent->GetWnd());
}
virtual wxWindow* GetWnd()const override
{
return mPanel;
}
void SetWhModel(const wh::SptrIModel& wh_model)const
{
mPanel->SetModel(wh_model);
}
};
//---------------------------------------------------------------------------
//typedef CtrlWindowBase<ViewPageUserList, ModelPageUserList> CtrlPageUserList;
class CtrlPageUserList : public CtrlWindowBase<ViewPageUserList, ModelPageUserList>
{
public:
CtrlPageUserList(std::shared_ptr<ViewPageUserList> view
, std::shared_ptr<ModelPageUserList> model)
:CtrlWindowBase(view, model)
{
view->SetWhModel(model->GetWhModel());
model->GetWhModel()->Load();
}
};
//---------------------------------------------------------------------------
} //namespace mvp{
#endif // __IMVP_H
|
#include <iostream>
using namespace std;
int main()
{
typedef unsigned int udb;
udb i = 5 , j = 2;
cout << " Nilai i = " << i;
cout << "Nilai j = " << j;
return 0;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Character/CSCharacter.h"
#include "CSAdvancedAI.generated.h"
/**
*
*/
UCLASS()
class UE4COOP_API ACSAdvancedAI : public ACSCharacter
{
GENERATED_BODY()
public:
/** Initialize Default Values */
ACSAdvancedAI();
public:
/** Behavior of this AI */
UPROPERTY(EditAnywhere, Category = Behavior)
class UBehaviorTree* AIBehavior;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef DESKTOPOPSYSTEMINFO_H
#define DESKTOPOPSYSTEMINFO_H
#include "adjunct/desktop_util/prefs/DesktopPrefsTypes.h"
#include "modules/pi/OpBitmap.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/prefs/prefsmanager/prefstypes.h"
#define g_desktop_op_system_info static_cast<DesktopOpSystemInfo*>(g_op_system_info)
class ExternalDownloadManager;
/**
* DesktopOpSystemInfo extends the OpSystemInfo porting interface
* with functionality specific for the desktop projects.
*/
class DesktopOpSystemInfo : public OpSystemInfo
{
public:
/* Public constant*/
typedef enum PLATFORM_IMAGE
{
PLATFORM_IMAGE_SHIELD = 0,
PLATFORM_IMAGE_LAST,
} PLATFORM_IMAGE;
typedef enum PRODUCT_TYPE
{
PRODUCT_TYPE_OPERA = 0,
PRODUCT_TYPE_OPERA_NEXT,
PRODUCT_TYPE_OPERA_LABS
} PRODUCT_TYPE;
/** Which browser is set as default in the OS. */
typedef enum DefaultBrowser
{
DEFAULT_BROWSER_UNKNOWN,
DEFAULT_BROWSER_FIREFOX,
DEFAULT_BROWSER_IE,
DEFAULT_BROWSER_OPERA
} DefaultBrowser;
public:
/**
* Return the time limit in milliseconds that distinguishes a double click
* from two consecutive mouse clicks.
*
* @return int Double click time limit in milliseconds
*/
virtual int GetDoubleClickInterval() = 0;
/**
* Get info about the content type of a file - name of contenttype and icon for it.
*
* @param filename - name of file (eg. document.pdf)
* @param content_type - contenttype of file
* @param content_type_name - an OpString where the textual description of mimetype of
* file should be placed (eg. "PDF document")
* @param content_type_bitmap - reference to an OpBitmap pointer where the icon should be placed
* @param content_type_bitmap_size - the required size of the icon
* @return OpStatus::OK if filetype info was found
*/
virtual OP_STATUS GetFileTypeInfo(const OpStringC& filename,
const OpStringC& content_type,
OpString & content_type_name,
OpBitmap *& content_type_bitmap,
UINT32 content_type_bitmap_size = 16) = 0;
/**
* Get a list of handlers for the given content_type/filename
*
* @param filename The filename of the file to be handled
* @param content_type The content type of the file to be handled
* @param handlers The vector of commands to start the handlers
* @param handler_names The vector of human friendly names for the handlers
* @param handler_icons The vector of bitmaps of icons for the handlers
* @param type The type of URL to be opened (eg URL_HTTP or URL_FILE)
*
* Note 1:
* These vectors have to match, that is:
* handlers.Get(i) is the command for the application called
* handler_names.Get(i) with the icon handler_icons.Get(i)
*
* Note 2: The icons should be 16*16 pixels
*/
virtual OP_STATUS GetFileHandlers(const OpString& filename,
const OpString &content_type,
OpVector<OpString>& handlers,
OpVector<OpString>& handler_names,
OpVector<OpBitmap>& handler_icons,
URLType type,
UINT32 icon_size = 16) = 0;
/**
* Starts up an application displaying the folder of the file, and highlighting the file specified.
*
* @param file_path - the full path to the file
* @param treat_folders_as_files - if TRUE and file_path is a path to a directory,
* the parent directory is opened, with the highlighting the folder.
* if FALSE, the path to the directory specified is opened.
*
* @return OpStatus::OK if successful
*/
virtual OP_STATUS OpenFileFolder(const OpStringC & file_path, BOOL treat_folders_as_files = TRUE) = 0;
/**
* @return TRUE if platform allows running downloaded content.
*/
virtual BOOL AllowExecuteDownloadedContent() = 0;
/** Return a string containing all characters illegal for use in a filename.
*
* NOTE: This method is being considered for removal. Please
* refrain from using it from core code.
*/
virtual OP_STATUS GetIllegalFilenameCharacters(OpString* illegalchars) = 0;
/** Cleans a path of illegal characters.
*
* Any spaces in front and in the end will be removed as well.
*
* NOTE: This method is being considered for removal. Please
* refrain from using it from core code.
*
* @param path (in/out) Path from which to remove illegal characters.
* @param replace Replace illegal characters with a valid
* character if TRUE. Otherwise remove the illegal character.
* @return TRUE if the returned string is non-empty
*/
virtual BOOL RemoveIllegalPathCharacters(OpString& path, BOOL replace) = 0;
/** Cleans a filename for illegal characters. On most platforms these illegal
* characters will include things like path seperator characters for example.
*
* Any spaces in front and in the end will be removed as well.
*
* @param path (in/out) filename from which to remove illegal characters.
* @param replace Replace illegal characters with a valid
* character if TRUE. Otherwise remove the illegal character.
* @return TRUE if the returned string is non-empty
*/
virtual BOOL RemoveIllegalFilenameCharacters(OpString& path, BOOL replace) = 0;
# ifdef EXTERNAL_APPLICATIONS_SUPPORT
# ifdef DU_REMOTE_URL_HANDLER
/** Implement the OpSystemInfo::ExecuteApplication method, and thereby intercept the platform
* the platform must implement PlatformExecuteApplication
*/
OP_STATUS ExecuteApplication(const uni_char* application,
const uni_char* args,
BOOL silent_errors = FALSE);
/** Execute an external application.
*
* @param application Application name
* @param args Arguments to the application
* @param silent_errors If TRUE, the platform should not show any UI to
* the user in the event of errors; caller shall handle all errors
* and a platform dialog would only confuse the user. When FALSE,
* the platform may show a UI on errors but need not.
*
* @retval OK
* @retval ERR_NO_MEMORY
* @retval ERR
*/
virtual OP_STATUS PlatformExecuteApplication(const uni_char* application,
const uni_char* args,
BOOL silent_errors) = 0;
/** Open given single file using application.
* Filename will surrounded with quotation marks before passing as
* application argument.
*
* @param application Application name
* @param filename Argument to the application
*/
OP_STATUS OpenFileInApplication(const uni_char* application, const uni_char* filename);
# endif // DU_REMOTE_URL_HANDLER
# endif // EXTERNAL_APPLICATIONS_SUPPORT
# ifdef EXTERNAL_APPLICATIONS_SUPPORT
/**
* Execute a dedicated application that handles this kind of URL.
* Usually it's not an HTTP URL, but a different protocol.
* For example, if iTunes is installed, the "itms://" protocol is registered in the system.
* Another typical example is "skype://".
* Usually the URL is passed as the argument to the protocol handler program.
*
* Note to implementations :
* The URL argument is destroyed right after the call.
* If you want to store a pointer, you must increase the reference count or make a copy.
*
* @param url URL to open
* @return error code
*/
virtual OP_STATUS OpenURLInExternalApp(const URL& url) = 0;
# endif // EXTERNAL_APPLICATIONS_SUPPORT
/** Compose an email message with an external client, invoked when clicking mailto
*
* @param to To header for email to be created
* @param cc CC header for email to be created
* @param bcc BCC header for email to be created
* @param subject Subject header for email to be created
* @param message Body of the email message to be created
* @param raw_address The link that was clicked that triggered this action
* @param mailhandler Which mail handler to use to compose the message
*/
virtual void ComposeExternalMail(const uni_char* to, const uni_char* cc, const uni_char* bcc, const uni_char* subject, const uni_char* message, const uni_char* raw_address, MAILHANDLER mailhandler) = 0;
/**
* @return Whether there is a system tray available for Opera
*/
virtual BOOL HasSystemTray() = 0;
#ifdef QUICK_USE_DEFAULT_BROWSER_DIALOG
/** Implement methods to inquire if opera is set as default 'internet' browser
* and if not, then a method to set it as the default browser.
* FALSE means either opera is default browser, or we either are not, or it cannot be
* determined, and the user shall not be asked
* TRUE means either that opera is not the default browser or we don't know, but
* the user shall be asked if it shall be set as the default browser anyway */
virtual BOOL ShallWeTryToSetOperaAsDefaultBrowser() = 0;
virtual OP_STATUS SetAsDefaultBrowser() = 0;
#endif // QUICK_USE_DEFAULT_BROWSER_DIALOG
/**
* Get which browser is set as default in the OS.
*/
virtual DefaultBrowser GetDefaultBrowser() { return DEFAULT_BROWSER_UNKNOWN; }
/**
* Get path to bookmarks store of default browser.
*
* @param default_browser which browser is set as default in the OS
* @param location gets path to bookmarks store
*
* @return
* - OpStatus::OK on success
* - OpStatus::ERR_NOT_SUPPORTED if default_browser is not supported
* - OpStatus::ERR_NO_MEMORY on OOM
* - OpStatus::ERR on other errors
*/
virtual OP_STATUS GetDefaultBrowserBookmarkLocation(DefaultBrowser default_browser, OpString& location) { return OpStatus::ERR_NOT_SUPPORTED; }
/**
* Gets the language folder in the format for the system (i.e. Mac: en.lproj, Win/Unix: en)
* This is NOT the full path and does not check if the folder exists
*
* @param lang_code Language code for the system (e.g. German = de)
* @return folder_name Build folder name (e.g. de.lproj)
*/
virtual OpString GetLanguageFolder(const OpStringC &lang_code) = 0;
/** Gets the title to use in Opera's top-level browser windows
* @param title Title that can be used for Opera windows, eg. "Opera"
*/
virtual OP_STATUS GetDefaultWindowTitle(OpString& title) = 0;
/** Gets available external donwload managers(flashget, IDM etc) to use when downloading files.
* Some users prefer to use external tools to accelerate downloading, makes significant sense
* in particular markets, China for one. Platforms could cache the info so that it doesn't need
* to search for them everytime.
*
* @param download_managers Found available external download managers.
*/
virtual OP_STATUS GetExternalDownloadManager(OpVector<ExternalDownloadManager>& download_managers){return OpStatus::ERR;}
/** Get the amount of free physical memory in MB. Not used by desktop
*/
virtual OP_STATUS GetAvailablePhysicalMemorySizeMB(UINT32* result) { return OpStatus::ERR_NOT_SUPPORTED; }
/**
* Fetchs an icon.
*
* @param icon_id (input) ID of an image/icon.
* @param image (output) Contains image if retrieved successfully.
*
* @return OK if image is fetched successfully.
*/
virtual OP_STATUS GetImage(PLATFORM_IMAGE icon_id, Image &image) { return OpStatus::ERR_NOT_SUPPORTED; }
/**
* Introduced temporarily as a work around for DSK-337037.
* This function should end any Menu created by plugin if it starts a message loop. On
* Windows we just call EndMenu indiscriminately to keep it simple.
*
* When a plugin is running a nested message loop, any operation that deletes the document
* will crash Opera, some of these operations are closing and going back/forward etc.
* This should be fixed in core but considering the amount of dupes a quick workaround
* in Desktop is worthwhile.
*
*/
virtual OP_STATUS CancelNestedMessageLoop() { return OpStatus::OK; }
/**
* Get whether the app is in a state where window.open and friends should be forced as tab.
* Used in fullscreen and kiosk modes on Mac, where normally all js windows are toplevel windows.
*/
virtual BOOL IsForceTabMode() { return FALSE; }
/**
* Get whether the app is in sandbox environment in term of system sandbox (Apple like),
* not application sandbox (Chrome like).
*/
virtual BOOL IsSandboxed() { return FALSE; }
/**
* Get whether app is capable of content sharing using system api
*/
virtual BOOL SupportsContentSharing() { return FALSE; }
#ifdef PIXEL_SCALE_RENDERING_SUPPORT
/**
* Return the maximum scale factor in percent that will be used for the pixel scaler when
* PIXEL_SCALE_RENDERING_SUPPORT is in use. When multplie screens are in use, it should
* return the highest scale factor for all of them.
*/
virtual INT32 GetMaximumHiresScaleFactor() { return 100; }
#endif // PIXEL_SCALE_RENDERING_SUPPORT
/**
* Get fingerprint string for the system hardware.
* Fingerprints are used by search protection mechanism to prevent
* redistribution of search protection data by third-party software.
* Implementaion can return empty string if fingerprint can't or shouldn't
* be generated.
*/
virtual OP_STATUS GetHardwareFingerprint(OpString8& fingerprint)
{
fingerprint.Empty();
return OpStatus::OK;
}
virtual OpFileFolder GetDefaultSpeeddialPictureFolder() { return OPFILE_PICTURES_FOLDER; }
};
#endif // DESKTOPOPSYSTEMINFO_H
|
#include <iostream>
#include <string>
bool check(int day,int month) {
if(1 > month || 12 < month || 1 > day) {
return false;
}
if((1 == month || 3 == month || 5 == month || 7 == month || 8 == month || 10 == month || 12 == month) && 31 < day) {
return false;
} else if(2 == month && 28 < day) {
return false;
} else if((4 == month || 6 == month || 9 == month || 11 == month) && 30 < day) {
return false;
} else {
return true;
}
}
int main() {
int year = 0;
int day = 0;
char simbol;
int month = 0;
int x = 0;
std::cout<<"Mutqagrel Vini-i cnndyan or@. Orinak 2018 28-03 -> ";
std::cin>>year>>day>>simbol>>month;
x = day;
if(check(day,month) == true){
if(10 > month) {
day = month * 10;
} else {
day = (month % 10) * 10 + month / 10;
}
if(10 > x) {
month = x * 10;
} else {
month = (x % 10) * 10 + x / 10;
}
if(check(day,month) == true) {
std::cout<<"Kgan "<<year<<" "<<day<<'-'<<month<<std::endl;
} else {
std::cout<<"Aydpisi Or goyutyun chuni vorpisi gan"<<std::endl;
}
} else {
std::cout<<"Sxal mutqagrum "<<std::endl;
}
return 0;
}
|
/*******************************************************************
* Neural Network Training Example
* ------------------------------------------------------------------
* Bobby Anguelov - takinginitiative.wordpress.com (2008)
* MSN & email: banguelov@cs.up.ac.za
*********************************************************************/
//standard libraries
#include <iostream>
#include <ctime>
#include <sstream>
#include <fstream>
//custom includes
#include "modules/matrix_maths.h"
#include "modules/neuralNetwork.h"
#include "modules/neuralNetworkTrainer.h"
//use standard namespace
using namespace std;
int main()
{
//seed random number generator
srand( (unsigned int) time(0) );
//Training condition
int max_epoch = 10000000;
double accuracy = 99.9;
double max_time = 3000;
float lr = 0.001;
float momentum = 0.9;
float tRatio = 0.8;
float vRatio = 0.2;
//Layer Construction
vector<ConvLayer> CLayer;
vector<int> FCLayer{128};
// for data
int nInput = 25*25*3;
int nOutput = 3;
//create data set reader and load data file
dataReader d;
d.loadDataFile4Train("imgdata.txt",nInput,nOutput,tRatio,vRatio,NML);
d.setCreationApproach( STATIC, 1 );
//create neural network
neuralNetwork nn(nInput,FCLayer,nOutput);
//save the Training Condition
char file_name[255];
int file_no = 0;
sprintf(file_name,"log/condition%d.csv",file_no);
for ( int i=0 ; i < 100 ; i++ )
{
ifstream test(file_name);
if (!test) break;
file_no++;
sprintf(file_name,"log/condition%d.csv",file_no);
}
//create neural network trainer and save log
neuralNetworkTrainer nT( &nn );
nT.setTrainingParameters(lr, momentum, true);
nT.setStoppingConditions(max_epoch, accuracy, max_time);
ofstream logTrain;
logTrain.open(file_name,ios::out);
if ( logTrain.is_open() )
{
logTrain << "Input" << "," << nInput << endl;
if(CLayer.size()!=0){
logTrain << "ConvLayer" << "," << CLayer.size() << endl;
for (int i=0; i<CLayer.size(); i++)
logTrain << "Kernel["<< i << "]," << CLayer[i].nKernel << "," << CLayer[i].sKernel << "x" << CLayer[i].sKernel << ","<< CLayer[i].pdim << endl;
}
logTrain << "FCLayer" << "," << FCLayer.size() << endl;
for (int i=0; i<FCLayer.size(); i++) logTrain << "Neuron["<< i << "]," << FCLayer[i] << endl;
logTrain << "Output" << "," << nOutput << endl;
logTrain << "TrainingSet" << "," << (int)d.trainingDataEndIndex << endl;
logTrain << "ValidationSet" << "," << (int)((d.trainingDataEndIndex/tRatio)*vRatio) << endl;
logTrain << "Accuracy(%)" << "," << accuracy << endl;
logTrain << "Learning_rate" << "," << lr << endl;
logTrain << "Momentum" << "," << momentum << endl;
logTrain.close();
}
ostringstream log_name;
log_name << "log/log" << file_no << ".csv";
const char* log_name_char = new char[log_name.str().length()+1];
log_name_char = log_name.str().c_str();
nT.enableLogging(log_name_char, 10);
char w_name[255];
sprintf(w_name,"log/weights%d.txt",file_no);
nn.enableLoggingWeight(w_name); // ((#input)*(#neuron)+(#neuron)*(#output)--Weight)+((#neuron+#output)--Bias)
//train neural network on data sets
for (int i=0; i < d.getNumTrainingSets(); i++ )
{
nT.trainNetwork( d.getTrainingDataSet() );
}
CLayer.clear();
//print success
cout << endl << "Neuron weights saved to '" << w_name << "'" << endl;
cout << endl << endl << "-- END OF PROGRAM --" << endl;
}
|
/* -*- 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.
*/
#include "core/pch.h"
#include "modules/database/src/opdatabase_base.h"
#ifdef DATABASE_MODULE_MANAGER_SUPPORT
#include "modules/database/opdatabasemanager.h"
#include "modules/database/ps_commander.h"
#include "modules/database/prefscollectiondatabase.h"
#include "modules/database/opdatabase.h"
#include "modules/database/src/webstorage_data_abstraction_simple_impl.h"
#include "modules/hardcore/mh/messages.h"
#include "modules/hardcore/mh/mh.h"
#include "modules/libcrypto/include/CryptoHash.h"
#include "modules/prefsfile/prefsfile.h"
#include "modules/util/opfile/opfile.h"
#include "modules/util/opstrlst.h"
#include "modules/prefsfile/prefsentry.h"
#include "modules/prefsfile/prefssection.h"
#include "modules/formats/base64_decode.h"
#ifdef EXTENSION_SUPPORT
# include "modules/gadgets/OpGadgetManager.h"
#endif // EXTENSION_SUPPORT
const uni_char g_ps_memory_file_name[] = {':','m','e','m','o','r','y',':',0};
PS_IndexIterator::PS_IndexIterator(PS_Manager* mgr, URL_CONTEXT_ID context_id,
PS_ObjectType use_case_type, const uni_char* origin,
BOOL only_persistent, IterationOrder order) :
m_order_type(order),
m_psobj_type(use_case_type),
m_origin(origin),
m_context_id(context_id),
m_last_mod_count(0),
m_1st_lvl_index(0),
m_2nd_lvl_index(0),
m_3rd_lvl_index(0),
m_sorted_index(NULL),
m_mgr(mgr)
{
if (only_persistent)
SetFlag(PERSISTENT_DB_ITERATOR);
OP_ASSERT(mgr != NULL);
}
PS_IndexIterator::~PS_IndexIterator()
{
UnsetFlag(OBJ_INITIALIZED | OBJ_INITIALIZED_ERROR);
if (m_sorted_index != NULL)
{
OP_DELETE(m_sorted_index);
m_sorted_index = NULL;
}
m_mgr = NULL;
}
void PS_IndexIterator::ResetL()
{
OP_ASSERT(m_mgr != NULL);
m_last_mod_count = m_mgr->GetModCount();
if (IsOrdered())
m_1st_lvl_index = 0;
else
m_1st_lvl_index = (m_psobj_type != KDBTypeStart ? m_psobj_type : KDBTypeStart + 1);
m_2nd_lvl_index = 0;
m_3rd_lvl_index = 0;
if (PeekCurrentL() == NULL)
MoveNextL();
}
void PS_IndexIterator::BuildL()
{
DB_ASSERT_RET(!IsInitialized(),);
SetFlag(OBJ_INITIALIZED);
if (IsOrdered())
{
OP_ASSERT(m_mgr != NULL);
OP_ASSERT(!m_sorted_index);
//build sorted stuff
OpStackAutoPtr<OpVector<PS_IndexEntry> > sorted_index_ptr(OP_NEW_L(OpVector<PS_IndexEntry>, ()));
OpStackAutoPtr<PS_IndexIterator> unordered_iterator_ptr(m_mgr->GetIteratorL(
m_context_id, m_psobj_type, GetFlag(PERSISTENT_DB_ITERATOR), UNORDERED));
OP_ASSERT(unordered_iterator_ptr.get());
OP_STATUS status;
if (!unordered_iterator_ptr->AtEndL())
{
do {
PS_IndexEntry* elem = unordered_iterator_ptr->GetItemL();
OP_ASSERT(elem != NULL);
if (GetFlag(PERSISTENT_DB_ITERATOR) && elem->IsMemoryOnly())
continue;
OP_ASSERT(m_context_id == DB_NULL_CONTEXT_ID || m_context_id == elem->GetUrlContextId());
if (m_origin != NULL &&
!OpDbUtils::StringsEqual(m_origin, elem->GetOrigin()))
continue;
status = sorted_index_ptr->Add(elem);
if (OpStatus::IsError(status))
{
m_order_type = UNORDERED;//not ordered, collection is empty
m_sorted_index = NULL;
LEAVE(SIGNAL_OP_STATUS_ERROR(status));
}
} while(unordered_iterator_ptr->MoveNextL());
sorted_index_ptr->QSort(m_order_type == ORDERED_ASCENDING ? PS_IndexEntry::CompareAsc : PS_IndexEntry::CompareDesc);
m_sorted_index = sorted_index_ptr.release();
}
else
{
m_order_type = UNORDERED;
m_1st_lvl_index = KDBTypeEnd;//optimization to prevent doing the full array loop
}
//else //no items ?? bah !
}
ResetL();
}
void PS_IndexIterator::ReSync()
{
if (m_last_mod_count != m_mgr->GetModCount())
{
m_last_mod_count = m_mgr->GetModCount();
if (PeekCurrentL() == NULL)
MoveNextL();
}
}
BOOL PS_IndexIterator::MoveNextL()
{
DB_ASSERT_LEAVE(IsInitialized(), PS_Status::ERR_INVALID_STATE);
//if the manager mutates, then the iterator becomes invalid
if (IsDesynchronized())
LEAVE(SIGNAL_OP_STATUS_ERROR(OpStatus::ERR_OUT_OF_RANGE));
if (AtEndL())
return FALSE;
if (IsOrdered())
{
do
{
m_1st_lvl_index++;
} while(PeekCurrentL() == NULL && !AtEndL());
}
else
{
OP_ASSERT(m_mgr != NULL);
PS_Manager::IndexByContext* mgr_data = m_mgr->GetIndex(m_context_id);
if (mgr_data != NULL)
{
PS_Manager::IndexEntryByOriginHash** const* db_index = mgr_data->m_object_index;
do {
//assert ensures that the array cannot be empty, else it should have been deleted
OP_ASSERT(db_index[m_1st_lvl_index] == NULL ||
db_index[m_1st_lvl_index][m_2nd_lvl_index] == NULL ||
db_index[m_1st_lvl_index][m_2nd_lvl_index]->m_objects.GetCount() != 0);
if (db_index[m_1st_lvl_index] == NULL ||
db_index[m_1st_lvl_index][m_2nd_lvl_index] == NULL ||
db_index[m_1st_lvl_index][m_2nd_lvl_index]->m_objects.GetCount() == 0 ||
db_index[m_1st_lvl_index][m_2nd_lvl_index]->m_objects.GetCount()-1 <= m_3rd_lvl_index)
{
if (PS_Manager::m_max_hash_amount - 1 <= m_2nd_lvl_index) {
m_1st_lvl_index = (m_psobj_type!=KDBTypeStart ? (unsigned)KDBTypeEnd : m_1st_lvl_index + 1);
m_2nd_lvl_index = 0;
}
else
{
m_2nd_lvl_index++;
}
m_3rd_lvl_index = 0;
}
else
{
m_3rd_lvl_index++;
}
} while(PeekCurrentL() == NULL && !AtEndL());
}
}
return !AtEndL();
}
BOOL PS_IndexIterator::AtEndL() const
{
DB_ASSERT_LEAVE(IsInitialized(), PS_Status::ERR_INVALID_STATE);
//if the manager mutates, then the iterator becomes invalid
if (IsDesynchronized())
LEAVE(SIGNAL_OP_STATUS_ERROR(OpStatus::ERR_OUT_OF_RANGE));
return IsOrdered() ?
m_sorted_index->GetCount() <= m_1st_lvl_index :
m_1st_lvl_index == KDBTypeEnd;
}
PS_IndexEntry* PS_IndexIterator::GetItemL() const
{
DB_ASSERT_LEAVE(IsInitialized(), PS_Status::ERR_INVALID_STATE);
//if the manager mutates, then the iterator becomes invalid
if (IsDesynchronized())
LEAVE(SIGNAL_OP_STATUS_ERROR(OpStatus::ERR_OUT_OF_RANGE));
if (AtEndL())
return NULL;
if (IsOrdered())
{
return m_sorted_index->Get(m_1st_lvl_index);
}
else
{
PS_Manager::IndexByContext* mgr_data = m_mgr->GetIndex(m_context_id);
OP_ASSERT(mgr_data != NULL);
//this method is called outside of the object, so we must ensure
//the iterator is pointing to a valid object, because
//multiple calls to GetItem should be as performant as possible
OP_ASSERT(mgr_data->m_object_index[m_1st_lvl_index] != NULL);
OP_ASSERT(mgr_data->m_object_index[m_1st_lvl_index][m_2nd_lvl_index] != NULL);
OP_ASSERT(mgr_data->m_object_index[m_1st_lvl_index][m_2nd_lvl_index]->m_objects.GetCount() > m_3rd_lvl_index);
return mgr_data->m_object_index[m_1st_lvl_index][m_2nd_lvl_index]->m_objects.Get(m_3rd_lvl_index);
}
}
BOOL PS_IndexIterator::IsDesynchronized() const
{
OP_ASSERT(m_last_mod_count == m_mgr->GetModCount());//this is the sort of stuff that shouldn't happen
return m_last_mod_count != m_mgr->GetModCount();
}
PS_IndexEntry* PS_IndexIterator::PeekCurrentL() const
{
if (IsDesynchronized())
LEAVE(SIGNAL_OP_STATUS_ERROR(OpStatus::ERR_OUT_OF_RANGE));
if (AtEndL())
return NULL;
if (IsOrdered())
{
return m_sorted_index->Get(m_1st_lvl_index);
}
else
{
//this method is called internally to check if the iterator is pointing to a valid
//object, hence the extra checks
PS_Manager::IndexByContext* mgr_data = m_mgr->GetIndex(m_context_id);
if (mgr_data != NULL)
{
PS_Manager::IndexEntryByOriginHash** const* db_index = mgr_data->m_object_index;
if (db_index[m_1st_lvl_index] != NULL)
if (db_index[m_1st_lvl_index][m_2nd_lvl_index] != NULL)
if (db_index[m_1st_lvl_index][m_2nd_lvl_index]->m_objects.GetCount() > m_3rd_lvl_index)
{
PS_IndexEntry* elem = db_index[m_1st_lvl_index][m_2nd_lvl_index]->m_objects.Get(m_3rd_lvl_index);
if (GetFlag(PERSISTENT_DB_ITERATOR) && elem->IsMemoryOnly())
return NULL;
OP_ASSERT(m_context_id == DB_NULL_CONTEXT_ID || m_context_id == elem->GetUrlContextId());
if (m_origin != NULL &&
!OpDbUtils::StringsEqual(m_origin, elem->GetOrigin()))
return NULL;
return elem;
}
}
}
return NULL;
}
/*************
* PS_DataFile
*************/
#define ENSURE_PATHSEPCHAR(buffer) do { \
if (buffer.Length()>0 && buffer.GetStorage()[buffer.Length()-1]!=PATHSEPCHAR) \
RETURN_IF_ERROR(buffer.Append(PATHSEPCHAR)); \
} while(0)
OP_STATUS
PS_DataFile::MakeAbsFilePath()
{
INTEGRITY_CHECK();
// Already have an absolute path. Just quit.
if (m_file_abs_path != NULL)
return OpStatus::OK;
OP_ASSERT(m_index_entry != NULL);
const uni_char* profile_folder = m_index_entry->GetPolicyAttribute(PS_Policy::KMainFolderPath);
RETURN_OOM_IF_NULL(profile_folder);
if (*profile_folder == 0)
return OpStatus::ERR_NO_ACCESS;
unsigned profile_folder_length = profile_folder != NULL ? uni_strlen(profile_folder) : 0;
uni_char *file_abs_path = NULL, *file_rel_path = NULL;
unsigned file_path_length = 0;
if (m_file_rel_path != NULL && OpDbUtils::IsFilePathAbsolute(m_file_rel_path))
{
// This file path is actually absolute, so we have everything we need. Skip ahead.
file_path_length = uni_strlen(m_file_rel_path);
file_abs_path = const_cast<uni_char*>(m_file_rel_path);
file_rel_path = const_cast<uni_char*>(m_file_rel_path);
}
else
{
TempBuffer buffer;
buffer.Clear();
buffer.SetCachedLengthPolicy(TempBuffer::TRUSTED);
uni_char folder_name[9] = {0}; /* ARRAY OK joaoe 2011-10-17 */
unsigned folder_number;
if (profile_folder != NULL)
{
RETURN_IF_ERROR(buffer.Append(profile_folder));
ENSURE_PATHSEPCHAR(buffer);
}
if (m_file_rel_path != NULL)
{
// We already have a relative file path to the storage folder
// which was read from the index file. Now we just need to resolve
// it to an absolute path.
RETURN_IF_ERROR(buffer.Append(m_file_rel_path));
OP_DELETEA(const_cast<uni_char*>(m_file_rel_path));
m_file_rel_path = NULL;
}
else
{
// No relative path means we need to look up a new file name
// that isn't occupied using the the following form
// * path_to_profile_folder/subfolder_if_any/xx/xx/xxxxxxxx
// Verbose:
// * path_to_profile_folder/subfolder_if_any/type_in_hex_2_chars/origin_hash_2_chars/data_file_name_8_chars_number_hex
RETURN_IF_ERROR(buffer.Append(m_index_entry->GetPolicyAttribute(PS_Policy::KSubFolder)));
ENSURE_PATHSEPCHAR(buffer);
folder_number = 0xff & m_index_entry->GetType();
uni_snprintf(folder_name, 9, UNI_L("%0.2X%c"), folder_number, PATHSEPCHAR);
RETURN_IF_ERROR(buffer.Append(folder_name, 3));
ENSURE_PATHSEPCHAR(buffer);
folder_number = 0xff & PS_Manager::HashOrigin(m_index_entry->GetOrigin());
uni_snprintf(folder_name, 9, UNI_L("%0.2X%c"), folder_number, PATHSEPCHAR);
RETURN_IF_ERROR(buffer.Append(folder_name, 3));
ENSURE_PATHSEPCHAR(buffer);
//calculate new file name using sequential numbering
unsigned current_length = buffer.Length();
buffer.SetCachedLengthPolicy(TempBuffer::UNTRUSTED);
OpFile test_file;
BOOL file_exists = FALSE;
RETURN_IF_ERROR(m_index_entry->GetPSManager()->MakeIndex(TRUE, m_index_entry->GetUrlContextId()));
PS_Manager::IndexByContext* mgr_data = m_index_entry->GetIndex();
OP_ASSERT(mgr_data != NULL);
OP_ASSERT(mgr_data->m_object_index[m_index_entry->GetType()] != NULL);
OP_ASSERT(mgr_data->m_object_index[m_index_entry->GetType()][PS_Manager::HashOrigin(m_index_entry->GetOrigin())] != NULL);
unsigned& m_highest_filename_number = mgr_data->
m_object_index[m_index_entry->GetType()][PS_Manager::HashOrigin(m_index_entry->GetOrigin())]->m_highest_filename_number;
// n_bad_tries tells the number of failed file accesses -
// like permissions failed or device not available
// n_good_tries tells when the calculated file name was being
// used by another file. However, in a normal situation this
// is unlikely to matter much because the code keeps track of
// the last file name and finds the one immediately after.
// This is useful if there are leftover files on the file system
// which are not in the index file.
unsigned n_bad_tries = 0, n_bad_tries_limit = 10;
unsigned n_good_tries = 0, n_good_tries_limit = 10000;
BOOL ok;
for (ok = TRUE; ok; ok = (n_bad_tries < n_bad_tries_limit && n_good_tries < n_good_tries_limit))
{
folder_number = m_highest_filename_number;
uni_snprintf(folder_name, 9, UNI_L("%0.8X"), folder_number);
RETURN_IF_ERROR(buffer.Append(folder_name));
// This will rollover from 0xffffffff to 0 and that's intended.
m_highest_filename_number++;
RETURN_IF_ERROR(test_file.Construct(buffer.GetStorage()));
if (OpStatus::IsSuccess(test_file.Exists(file_exists)))
{
DB_DBG(("File exists ? %s, %S\n", DB_DBG_BOOL(file_exists), buffer.GetStorage()));
if (!file_exists)
break;
}
else
{
n_bad_tries++;
DB_DBG(("Failed to access file: %S\n", buffer.GetStorage()));
}
n_good_tries++;
buffer.GetStorage()[current_length] = 0;
}
if (ok)
{
SetBogus(FALSE);
}
else
{
//whoops - can't access folder
m_file_abs_path = NULL;
m_file_rel_path = NULL;
SetBogus(TRUE);
return SIGNAL_OP_STATUS_ERROR(OpStatus::ERR_NO_ACCESS);
}
}
file_path_length = buffer.Length();
file_abs_path = OP_NEWA(uni_char, file_path_length + 1);
RETURN_OOM_IF_NULL(file_abs_path);
uni_strncpy(file_abs_path, buffer.GetStorage(), file_path_length);
file_abs_path[file_path_length] = 0;
file_rel_path = file_abs_path;
}
OP_ASSERT(file_abs_path != NULL);
OP_ASSERT(file_rel_path != NULL);
if (profile_folder_length < file_path_length && profile_folder_length != 0)
{
if (uni_strncmp(file_abs_path, profile_folder, profile_folder_length) == 0)
{
file_rel_path = file_abs_path + profile_folder_length;
if (file_rel_path[0] == PATHSEPCHAR)
file_rel_path++;
}
}
m_file_abs_path = file_abs_path;
m_file_rel_path = file_rel_path;
return InitFileObj();
}
OP_STATUS
PS_DataFile::EnsureDataFileFolder()
{
INTEGRITY_CHECK();
if (m_file_abs_path == NULL)
RETURN_IF_ERROR(SIGNAL_OP_STATUS_ERROR(MakeAbsFilePath()));
OP_ASSERT(m_file_abs_path != NULL);
const uni_char* path_sep_needle = uni_strrchr(m_file_abs_path, PATHSEPCHAR);
if (path_sep_needle != NULL)
{
uni_char file_abs_path_copy[_MAX_PATH+1]; /* ARRAY OK joaoe 2010-05-25 */
unsigned file_abs_path_copy_length = (unsigned)MIN(path_sep_needle - m_file_abs_path, _MAX_PATH);
uni_strncpy(file_abs_path_copy, m_file_abs_path, file_abs_path_copy_length);
file_abs_path_copy[file_abs_path_copy_length] = 0;
if (*file_abs_path_copy)
{
OpFile file;
RETURN_IF_ERROR(SIGNAL_OP_STATUS_ERROR(file.Construct(file_abs_path_copy)));
RETURN_IF_ERROR(SIGNAL_OP_STATUS_ERROR(file.MakeDirectory()));
}
}
return OpStatus::OK;
}
PS_DataFile::PS_DataFile(PS_IndexEntry* index_entry,
const uni_char* file_abs_path,
const uni_char* file_rel_path)
: m_index_entry(index_entry)
, m_file_abs_path(file_abs_path)
, m_file_rel_path(file_rel_path)
, m_bogus_file(FALSE)
, m_should_delete(FALSE)
{
DB_DBG_CHK(index_entry, ("%p: PS_DataFile::PS_DataFile(" DB_DBG_ENTRY_STR "): %d\n", this, DB_DBG_ENTRY_O(index_entry), GetRefCount()))
}
PS_DataFile::~PS_DataFile()
{
DB_DBG_CHK(m_index_entry, ("%p: PS_DataFile::~PS_DataFile(" DB_DBG_ENTRY_STR "): %d\n", this, DB_DBG_ENTRY_O(m_index_entry), GetRefCount()))
INTEGRITY_CHECK();
OP_ASSERT(GetRefCount() == 0);
if (m_file_abs_path != NULL && m_file_abs_path != g_ps_memory_file_name)
{
OP_DELETEA(const_cast<uni_char*>(m_file_abs_path));
}
else if (m_file_rel_path != NULL && m_file_rel_path != g_ps_memory_file_name)
{
OP_DELETEA(const_cast<uni_char*>(m_file_rel_path));
}
m_file_abs_path = m_file_rel_path = NULL;
if (m_index_entry != NULL && m_index_entry->m_data_file_name == this)
{
m_index_entry->m_data_file_name = NULL;
}
}
OP_STATUS
PS_DataFile::InitFileObj()
{
OP_ASSERT(m_file_abs_path == g_ps_memory_file_name ||
uni_strstr(m_file_abs_path, g_ps_memory_file_name) == NULL);
if (m_file_abs_path != NULL && m_file_abs_path != g_ps_memory_file_name)
return m_file_obj.Construct(m_file_abs_path);
return OpStatus::OK;
}
/*static*/
OP_STATUS
PS_DataFile::Create(PS_IndexEntry* index_entry, const uni_char* file_rel_path)
{
OP_ASSERT(index_entry != NULL);
OP_ASSERT(index_entry->m_data_file_name == NULL);
PS_DataFile* new_dfn;
if (index_entry->IsMemoryOnly())
{
new_dfn = &(index_entry->GetPSManager()->m_non_persistent_file_name_obj);
}
else
{
OP_ASSERT(file_rel_path == NULL || !OpDbUtils::StringsEqual(file_rel_path, g_ps_memory_file_name));
uni_char* file_rel_path_dupe = NULL;
if (file_rel_path != NULL)
{
file_rel_path_dupe = UniSetNewStr(file_rel_path);
RETURN_OOM_IF_NULL(file_rel_path_dupe);
}
new_dfn = OP_NEW(PS_DataFile,(index_entry, NULL, file_rel_path_dupe));
if (new_dfn == NULL)
{
OP_DELETEA(file_rel_path_dupe);
return SIGNAL_OP_STATUS_ERROR(OpStatus::ERR_NO_MEMORY);
}
}
OP_ASSERT(index_entry->m_data_file_name == NULL);
index_entry->m_data_file_name = new_dfn;
new_dfn->IncRefCount();
PS_DataFile_AddOwner(new_dfn, index_entry)
return OpStatus::OK;
}
void
PS_DataFile::SafeDelete()
{
DB_DBG_CHK(m_index_entry, ("%p: PS_DataFile::SafeDelete (" DB_DBG_ENTRY_STR "): %d\n", this, DB_DBG_ENTRY_O(m_index_entry), GetRefCount()))
INTEGRITY_CHECK();
if (GetRefCount() > 0)
return;
#ifdef SELFTEST
if (m_index_entry != NULL && m_index_entry->GetPSManager()->m_self_test_instance)
SetWillBeDeleted();
#endif
if (WillBeDeleted())
{
if (!m_file_abs_path && m_file_rel_path)
OpDbUtils::ReportCondition(MakeAbsFilePath());
if (GetOpFile() != NULL)
{
DB_DBG((" - deleting file %S\n", m_file_abs_path));
OpStatus::Ignore(GetOpFile()->Delete());
}
//TODO: delete folders if empty
}
DeleteSelf();
}
OP_STATUS
PS_DataFile::FileExists(BOOL *exists)
{
OP_ASSERT(exists);
RETURN_IF_ERROR(MakeAbsFilePath());
if (OpFile* data_file_obj = GetOpFile())
RETURN_IF_ERROR(data_file_obj->Exists(*exists));
else
*exists = FALSE;
return OpStatus::OK;
}
void
PS_MgrPrefsListener::PrefChanged(OpPrefsCollection::Collections id, int pref, int newvalue)
{
if (id != OpPrefsCollection::PersistentStorage)
return;
switch(pref)
{
#ifdef DATABASE_STORAGE_SUPPORT
case PrefsCollectionDatabase::DatabaseStorageQuotaExceededHandling:
m_last_type = KWebDatabases;
break;
#endif //DATABASE_STORAGE_SUPPORT
#ifdef WEBSTORAGE_ENABLE_SIMPLE_BACKEND
case PrefsCollectionDatabase::LocalStorageQuotaExceededHandling:
m_last_type = KLocalStorage;
break;
#ifdef WEBSTORAGE_WIDGET_PREFS_SUPPORT
case PrefsCollectionDatabase::WidgetPrefsQuotaExceededHandling:
m_last_type = KWidgetPreferences;
break;
#endif //WEBSTORAGE_WIDGET_PREFS_SUPPORT
#endif //WEBSTORAGE_ENABLE_SIMPLE_BACKEND
default:
m_last_type = KDBTypeStart;
}
//if this fails, there nothing much we can do...
OpDbUtils::ReportCondition(m_mgr->EnumerateContextIds(this));
}
void
PS_MgrPrefsListener::PrefChanged(OpPrefsCollection::Collections id, int pref, const OpStringC& newvalue)
{}
#ifdef PREFS_HOSTOVERRIDE
void
PS_MgrPrefsListener::HostOverrideChanged(OpPrefsCollection::Collections id, const uni_char* hostname)
{}
#endif
OP_STATUS
PS_MgrPrefsListener::HandleContextId(URL_CONTEXT_ID context_id)
{
if (m_last_type == KDBTypeStart)
return m_mgr->EnumerateTypes(this, context_id);
else
return m_mgr->EnumerateOrigins(this, context_id, m_last_type);
}
OP_STATUS
PS_MgrPrefsListener::HandleType(URL_CONTEXT_ID context_id, PS_ObjectType type)
{
OP_ASSERT(m_last_type == KDBTypeStart);
return m_mgr->EnumerateOrigins(this, context_id, type);
}
OP_STATUS
PS_MgrPrefsListener::HandleOrigin(URL_CONTEXT_ID context_id, PS_ObjectType type, const uni_char* origin)
{
m_mgr->InvalidateCachedDataSize(type, context_id, origin);
return OpStatus::OK;
}
void
PS_MgrPrefsListener::Clear()
{
if (m_current_listenee != NULL)
{
m_current_listenee->UnregisterListener(this);
m_current_listenee = NULL;
}
}
OP_STATUS
PS_MgrPrefsListener::Setup(OpPrefsCollection* listenee)
{
Clear();
if (listenee != NULL)
{
TRAP_AND_RETURN(status, listenee->RegisterListenerL(this));
m_current_listenee = listenee;
}
return OpStatus::OK;
}
/**
* repetition of the PS_ObjectType enumeration - because the
* integer associated with each enum might change for some reason
* it's easier to just write to the file the type as a human readable
* string than an integer.
* NOTE: the above means that once one adds a value to this array
* it can no longer change after it's being used in public product,
* else data files will apparently go missing for end users
*/
//the default one does not help much
#ifdef HAS_COMPLEX_GLOBALS
# define CONST_ARRAY_CLS(name, _, type) const type const name[] = {
#else
# define CONST_ARRAY_CLS(fn, name, type) void init_##fn () { const type* local = const_cast<const type*>(name); int i = 0;
#endif // HAS_COMPLEX_GLOBALS
CONST_ARRAY_CLS(database_module_mgr_psobj_types, g_database_manager->GetTypeDescTable(), uni_char*)
#ifdef WEBSTORAGE_ENABLE_SIMPLE_BACKEND
CONST_ENTRY(UNI_L("localstorage")), //KLocalStorage
CONST_ENTRY(UNI_L("sessionstorage")), //KSessionStorage
#endif //WEBSTORAGE_ENABLE_SIMPLE_BACKEND
#ifdef DATABASE_STORAGE_SUPPORT
CONST_ENTRY(UNI_L("webdatabase")), //KWebDatabases
#endif //DATABASE_STORAGE_SUPPORT
#ifdef WEBSTORAGE_WIDGET_PREFS_SUPPORT
CONST_ENTRY(UNI_L("widgetpreferences")), //KWidgetPreferences
#endif //WEBSTORAGE_WIDGET_PREFS_SUPPORT
#ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
CONST_ENTRY(UNI_L("userscript")), //KUserJsStorage
#endif //WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
CONST_ENTRY(NULL)
#ifndef HAS_COMPLEX_GLOBALS
;
#define database_module_mgr_psobj_types (g_database_manager->GetTypeDescTable())
#endif //HAS_COMPLEX_GLOBALS
CONST_END(database_module_mgr_psobj_types)
#ifdef SQLITE_SUPPORT
const OP_STATUS op_database_manager_sqlite_to_opstatus[27] =
{
PS_Status::OK, //SQLITE_OK 0 /* Successful result */
PS_Status::ERR_BAD_QUERY, //SQLITE_ERROR 1 /* SQL error or missing database */
PS_Status::ERR, //SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
PS_Status::ERR_NO_ACCESS, //SQLITE_PERM 3 /* Access permission denied */
PS_Status::ERR_TIMED_OUT, //SQLITE_ABORT 4 /* Callback routine requested an abort */
PS_Status::ERR_YIELD, //SQLITE_BUSY 5 /* The ps_obj file is locked */
PS_Status::ERR_YIELD, //SQLITE_LOCKED 6 /* A table in the ps_obj is locked */
PS_Status::ERR_NO_MEMORY, //SQLITE_NOMEM 7 /* A malloc() failed */
PS_Status::ERR_READ_ONLY, //SQLITE_READONLY 8 /* Attempt to write a readonly ps_obj */
PS_Status::ERR_TIMED_OUT, //SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
PS_Status::ERR_NO_ACCESS, //SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
PS_Status::ERR_CORRUPTED_FILE, //SQLITE_CORRUPT 11 /* The ps_obj disk image is malformed */
PS_Status::OK, //SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */
PS_Status::ERR_QUOTA_EXCEEDED, //SQLITE_FULL 13 /* Insertion failed because ps_obj is full */
PS_Status::ERR_NO_ACCESS, //SQLITE_CANTOPEN 14 /* Unable to open the ps_obj file */
PS_Status::OK, //SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */
PS_Status::ERR_BAD_QUERY, //SQLITE_EMPTY 16 /* Database is empty */
PS_Status::ERR_VERSION_MISMATCH, //SQLITE_SCHEMA 17 /* The ps_obj schema changed */
PS_Status::ERR_BAD_BIND_PARAMETERS, //SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
PS_Status::ERR_CONSTRAINT_FAILED, //SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
PS_Status::ERR_BAD_QUERY, //SQLITE_MISMATCH 20 /* Data type mismatch */
PS_Status::ERR, //SQLITE_MISUSE 21 /* Library used incorrectly */
PS_Status::ERR_NOT_SUPPORTED, //SQLITE_NOLFS 22 /* Uses OS features not supported on host */
PS_Status::ERR_AUTHORIZATION, //SQLITE_AUTH 23 /* Authorization denied */
PS_Status::ERR, //SQLITE_FORMAT 24 /* Auxiliary ps_obj format error */
PS_Status::ERR_BAD_BIND_PARAMETERS, //SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
PS_Status::ERR_CORRUPTED_FILE //SQLITE_NOTADB 26 /* File opened that is not a ps_obj file */
};
#endif //SQLITE_SUPPORT
#ifdef DEBUG_ENABLE_OPASSERT
BOOL op_database_manager_type_desc_validate(unsigned length)
{
BOOL ok = TRUE;
for(unsigned idx = 0; idx < length; idx++)
ok = ok && database_module_mgr_psobj_types[idx] != NULL && *database_module_mgr_psobj_types[idx];
return ok;
}
#endif // DEBUG_ENABLE_OPASSERT
#ifdef SQLITE_SUPPORT
OP_STATUS
PS_Manager::SqliteErrorCodeToOpStatus(SQLiteErrorCode err_code)
{
unsigned u_err_code = 0x3f & (unsigned)op_abs(err_code);
return ARRAY_SIZE(op_database_manager_sqlite_to_opstatus) <= u_err_code ?
OpStatus::OK : op_database_manager_sqlite_to_opstatus[u_err_code];
}
#endif //SQLITE_SUPPORT
/// the manager
PS_Manager::PS_Manager() :
#ifdef SELFTEST
m_self_test_instance(FALSE),
#endif //SELFTEST
m_modification_counter(0),
m_last_save_mod_counter(0),
m_inside_enumerate_count(0),
m_prefs_listener(this)
{}
#ifdef SELFTEST
PS_Manager* PS_Manager::NewForSelfTest()
{
PS_Manager *mgr = OP_NEW(PS_Manager, ());
if (mgr != NULL)
mgr->m_self_test_instance = TRUE;
return mgr;
}
#endif //SELFTEST
TempBuffer& PS_Manager::GetTempBuffer(BOOL clear)
{
if (clear)
m_global_buffer.Clear();
return m_global_buffer;
}
OP_STATUS PS_Manager::EnsureInitialization()
{
if (IsInitialized())
return OpStatus::OK;
OP_ASSERT(!GetFlag(BEING_DELETED) && IsOperaRunning() && GetMessageHandler() != NULL);
RETURN_IF_ERROR(AddContext(DB_MAIN_CONTEXT_ID, OPFILE_PERSISTENT_STORAGE_FOLDER, false));
#ifdef SELFTEST
if (!m_self_test_instance)
#endif //SELFTEST
{
OpMessage messages[2] = {MSG_DB_MANAGER_FLUSH_INDEX_ASYNC, MSG_DB_MODULE_DELAYED_DELETE_DATA};
RETURN_IF_ERROR(GetMessageHandler()->SetCallBackList(this, GetMessageQueueId(), messages, ARRAY_SIZE(messages)));
RETURN_IF_ERROR(m_prefs_listener.Setup(g_pcdatabase));
}
OP_ASSERT(m_inside_enumerate_count == 0);
m_last_save_mod_counter = ++m_modification_counter;
CONST_ARRAY_INIT(database_module_mgr_psobj_types);
OP_ASSERT(op_database_manager_type_desc_validate(DATABASE_INDEX_LENGTH));//ensure it's well built
SetFlag(OBJ_INITIALIZED);
return OpStatus::OK;
}
OP_STATUS
PS_Manager::AddContext(URL_CONTEXT_ID context_id, OpFileFolder root_folder_id, bool extension_context)
{
DB_DBG(("PS_Manager::AddContext(): %u, %u\n", context_id, root_folder_id));
// Calling this multiple times is supported because the code flow in core is quite complex
// so it should make stuff easier for the API user. However, the values passed need to be
// consistent, else there is trouble.
#ifdef EXTENSION_SUPPORT
OP_ASSERT(GetIndex(context_id) == NULL || !GetIndex(context_id)->m_bools.is_extension_context || extension_context);
#endif // EXTENSION_SUPPORT
OP_ASSERT(GetIndex(context_id) == NULL || !GetIndex(context_id)->WasRegistered() || GetIndex(context_id)->m_context_folder_id == root_folder_id);
// NOTE: cannot load file now. It would be useless overhead
// because this call will happen during core initialization,
// and because the folder id and the was_registered flags
// are only set after.
RETURN_IF_ERROR(MakeIndex(FALSE, context_id));
IndexByContext *ctx = GetIndex(context_id);
OP_ASSERT(ctx);
ctx->m_context_folder_id = root_folder_id;
ctx->m_bools.was_registered = true;
#ifdef EXTENSION_SUPPORT
ctx->m_bools.is_extension_context = extension_context;
#endif // EXTENSION_SUPPORT
return OpStatus::OK;
}
bool
PS_Manager::IsContextRegistered(URL_CONTEXT_ID context_id) const
{
IndexByContext *ctx = GetIndex(context_id);
return ctx != NULL && ctx->WasRegistered();
}
#ifdef EXTENSION_SUPPORT
bool
PS_Manager::IsContextExtension(URL_CONTEXT_ID context_id) const
{
IndexByContext *ctx = GetIndex(context_id);
return ctx != NULL && ctx->WasRegistered() && ctx->IsExtensionContext();
}
#endif // EXTENSION_SUPPORT
BOOL
PS_Manager::GetContextRootFolder(URL_CONTEXT_ID context_id, OpFileFolder* root_folder_id)
{
OP_ASSERT(root_folder_id);
IndexByContext *ctx = GetIndex(context_id);
if (ctx == NULL)
return FALSE;
// The non-default context id needs to be registered using AddContext
// Else the folder will be bogus.
OP_ASSERT(ctx->WasRegistered());
if (!ctx->WasRegistered())
return FALSE;
*root_folder_id = ctx->m_context_folder_id;
return TRUE;
}
void
PS_Manager::RemoveContext(URL_CONTEXT_ID context_id)
{
DropEntireIndex(context_id);
}
void PS_Manager::Destroy()
{
OP_ASSERT(m_inside_enumerate_count == 0);
#ifdef DATABASE_MODULE_DEBUG
#ifdef SELFTEST
if (!m_self_test_instance)
#endif //SELFTEST
{
TRAPD(status_dummy_ignore,DumpIndexL(DB_NULL_CONTEXT_ID, UNI_L("PS_Manager::~Destroy()")));
}
#endif // DATABASE_MODULE_DEBUG
SetFlag(BEING_DELETED);
if (GetFlag(OBJ_INITIALIZED))
{
if (GetMessageHandler() != NULL)
GetMessageHandler()->UnsetCallBacks(this);
FlushDeleteQueue(FALSE);
m_prefs_listener.Clear();
DropEntireIndex();
}
m_object_index.DeleteAll();
OP_ASSERT(m_object_index.GetCount() == 0);
UnsetFlag(OBJ_INITIALIZED | OBJ_INITIALIZED_ERROR);
m_last_save_mod_counter = ++m_modification_counter;
}
/*static*/ OP_STATUS
PS_Manager::CheckOrigin(PS_ObjectType type, const uni_char* origin, BOOL is_persistent)
{
if (origin == NULL || *origin == 0)
{
OP_ASSERT(!"Origin may not be blank");
return OpStatus::ERR_NULL_POINTER;
}
return OpStatus::OK;
}
OP_STATUS PS_Manager::GetObject(PS_ObjectType type, const uni_char* origin,
const uni_char* name, BOOL is_persistent, URL_CONTEXT_ID context_id, PS_Object** ps_obj)
{
OP_ASSERT(ValidateObjectType(type));
if (!ValidateObjectType(type))
return OpStatus::ERR_OUT_OF_RANGE;
OP_ASSERT(ps_obj != NULL);
unsigned access = g_database_policies->GetPolicyAttribute(type,
PS_Policy::KAccessToObject, context_id, origin);
if (access == PS_Policy::KAccessDeny)
return OpStatus::ERR_NO_ACCESS;
RETURN_IF_ERROR(CheckOrigin(type, origin, is_persistent));
RETURN_IF_ERROR(EnsureInitialization());
RETURN_IF_ERROR(MakeIndex(TRUE, context_id));
OP_ASSERT(GetIndex(context_id) != NULL && GetIndex(context_id)->WasRegistered());
if (!GetIndex(context_id)->WasRegistered())
return OpStatus::ERR_NO_ACCESS;
PS_IndexEntry* key = CheckObjectExists(type, origin,
name, is_persistent, context_id);
if (!key)
{
//before creating a new ps_obj, check that we're not passing the allowed limit
unsigned max_allowed_dbs = g_database_policies->GetPolicyAttribute(type,
PS_Policy::KMaxObjectsPerOrigin, context_id, origin);
if (max_allowed_dbs != 0 && max_allowed_dbs < GetNumberOfObjects(context_id, type, origin))
{
RETURN_IF_ERROR(PS_Status::ERR_MAX_DBS_PER_ORIGIN);
}
RETURN_IF_ERROR(StoreObject(type, origin, name,
NULL, NULL, is_persistent, context_id, &key));
}
if (key->m_ps_obj == NULL)
{
OP_ASSERT(key->GetRefCount() == 0);
PS_Object* o = PS_Object::Create(key);
RETURN_OOM_IF_NULL(o);
key->m_ps_obj = o;
}
key->IncRefCount();
key->UnmarkDeletion();
*ps_obj = key->m_ps_obj;
return OpStatus::OK;
}
OP_STATUS PS_Manager::DeleteObject(PS_ObjectType type,
const uni_char* origin,
const uni_char* name,
BOOL is_persistent, URL_CONTEXT_ID context_id)
{
RETURN_IF_ERROR(EnsureInitialization());
RETURN_IF_ERROR(MakeIndex(TRUE, context_id));
PS_IndexEntry* key = CheckObjectExists(type, origin, name, is_persistent, context_id);
if (key)
{
key->Delete();
return OpStatus::OK;
}
return OpStatus::ERR_OUT_OF_RANGE;
}
OP_STATUS
PS_Manager::DeleteObjects(PS_ObjectType type, URL_CONTEXT_ID context_id,
const uni_char *origin, BOOL only_persistent)
{
DB_DBG(("PS_Manager::DeleteObjects(): %s,%d,%S,%s\n", GetTypeDesc(type), context_id, origin, DB_DBG_BOOL(only_persistent)))
class DeleteItr : public PS_MgrContentIterator {
public:
PS_Manager *m_mgr;
BOOL m_only_persistent;
OpVector<PS_IndexEntry> m_objs;
DeleteItr(PS_Manager *mgr, BOOL only_persistent) : m_mgr(mgr), m_only_persistent(only_persistent){}
virtual OP_STATUS HandleOrigin(URL_CONTEXT_ID context_id, PS_ObjectType type, const uni_char* origin) {
return m_mgr->EnumerateObjects(this, context_id, type, origin);
}
virtual OP_STATUS HandleObject(PS_IndexEntry* object_entry) {
OP_ASSERT(object_entry);
if (!m_only_persistent || object_entry->IsPersistent())
return m_objs.Add(object_entry);
return OpStatus::OK;
}
} itr(this, only_persistent);
OP_STATUS status;
if (origin == NULL || origin[0] == 0)
status = EnumerateOrigins(&itr, context_id, type);
else
status = EnumerateObjects(&itr, context_id, type, origin);
for (unsigned k = 0, m = itr.m_objs.GetCount(); k < m; k++)
itr.m_objs.Get(k)->Delete();
return status;
}
OP_STATUS
PS_Manager::DeleteObjects(PS_ObjectType type, URL_CONTEXT_ID context_id, BOOL only_persistent)
{
return DeleteObjects(type, context_id, NULL, only_persistent);
}
OP_STATUS
PS_Manager::GetGlobalDataSize(OpFileLength* data_size, PS_ObjectType type,
URL_CONTEXT_ID context_id, const uni_char* origin)
{
OP_ASSERT(data_size != NULL);
TRAPD(status, *data_size = GetGlobalDataSizeL(type, context_id, origin));
return SIGNAL_OP_STATUS_ERROR(status);
}
OpFileLength
PS_Manager::GetGlobalDataSizeL(PS_ObjectType type, URL_CONTEXT_ID context_id, const uni_char* origin)
{
OP_ASSERT(IsInitialized());
LEAVE_IF_ERROR(MakeIndex(TRUE, context_id));
IndexByContext* mgr_data = GetIndex(context_id);
OP_ASSERT(mgr_data != NULL);
if (origin == NULL || origin[0] == 0)
{
if (mgr_data->m_cached_data_size[type] != FILE_LENGTH_NONE)
return mgr_data->m_cached_data_size[type];
}
IndexEntryByOriginHash* eoh = mgr_data->GetIndexEntryByOriginHash(type, origin);
if (eoh != NULL)
{
if (eoh->HasCachedDataSize(origin))
return eoh->GetCachedDataSize(origin);
if (eoh->GetNumberOfDbs(origin) == 0)
return 0;
}
PS_IndexIterator *iterator = GetIteratorL(context_id, type, origin,
TRUE, PS_IndexIterator::UNORDERED);
OP_ASSERT(iterator != NULL);
OpStackAutoPtr<PS_IndexIterator> iterator_ptr(iterator);
PS_IndexEntry *key;
OpFileLength fize_size_one = 0, fize_size_total = 0;
if (!iterator->AtEndL())
{
do
{
key = iterator->GetItemL();
if (key->GetPolicyAttribute(PS_Policy::KOriginExceededHandling, NULL) != PS_Policy::KQuotaAllow)
{
LEAVE_IF_ERROR(key->GetDataFileSize(&fize_size_one));
fize_size_total += fize_size_one;
}
} while(iterator->MoveNextL());
}
if (origin == NULL || origin[0] == 0)
{
mgr_data->m_cached_data_size[type] = fize_size_total;
}
else if (eoh != NULL)
{
LEAVE_IF_ERROR(eoh->SetCachedDataSize(origin, fize_size_total));
}
return fize_size_total;
}
void
PS_Manager::InvalidateCachedDataSize(PS_ObjectType type, URL_CONTEXT_ID context_id, const uni_char* origin)
{
IndexByContext* mgr_data = GetIndex(context_id);
if (mgr_data != NULL)
{
//global one
mgr_data->m_cached_data_size[type] = FILE_LENGTH_NONE;
IndexEntryByOriginHash *ci = mgr_data->GetIndexEntryByOriginHash(type, origin);
if (ci != NULL)
ci->UnsetCachedDataSize(origin);
}
}
#define DBFILE_ENTRY_TYPE UNI_L("Type")
#define DBFILE_ENTRY_TYPE_SZ 4
#define DBFILE_ENTRY_ORIGIN UNI_L("Origin")
#define DBFILE_ENTRY_ORIGIN_SZ 6
#define DBFILE_ENTRY_NAME UNI_L("Name")
#define DBFILE_ENTRY_NAME_SZ 4
#define DBFILE_ENTRY_FILE UNI_L("DataFile")
#define DBFILE_ENTRY_FILE_SZ 8
#define DBFILE_ENTRY_VERSION UNI_L("Version")
#define DBFILE_ENTRY_VERSION_SZ 7
void PS_Manager::ReadIndexFromFileL(const OpFile& file, URL_CONTEXT_ID context_id)
{
OP_ASSERT(!GetFlag(BEING_DELETED) && IsOperaRunning());
#ifdef SELFTEST
if (m_self_test_instance) return;
#endif //SELFTEST
m_modification_counter++;
PrefsFile prefs_file(PREFS_XML);
ANCHOR(PrefsFile, prefs_file);
prefs_file.ConstructL();
prefs_file.SetFileL(&file);
prefs_file.LoadAllL();
OpString entry_type, entry_origin, entry_name, entry_datafile, entry_db_version;
ANCHOR(OpString, entry_type);
ANCHOR(OpString, entry_origin);
ANCHOR(OpString, entry_name);
ANCHOR(OpString, entry_datafile);
ANCHOR(OpString, entry_db_version);
const uni_char *entry_name_str = NULL, *entry_db_version_str = NULL;
TempBuffer& buf = GetTempBuffer();
OP_STATUS status = OpStatus::OK;
OpString_list sections;
ANCHOR(OpString_list, sections);
prefs_file.ReadAllSectionsL(sections);
unsigned i, nr_of_sections = sections.Count();
for (i = 0; i < nr_of_sections; i++)
{
const OpString& current_section = sections.Item(i);
prefs_file.ReadStringL(current_section, DBFILE_ENTRY_TYPE, entry_type);
PS_ObjectType entry_type_number = GetDescType(entry_type.CStr());
if (!ValidateObjectType(entry_type_number))
continue;
prefs_file.ReadStringL(current_section, DBFILE_ENTRY_FILE, entry_datafile);
if (entry_datafile.IsEmpty())
continue;
prefs_file.ReadStringL(current_section, DBFILE_ENTRY_ORIGIN, entry_origin);
entry_name_str = NULL;
if (prefs_file.IsKey(current_section.CStr(), DBFILE_ENTRY_NAME))
{
prefs_file.ReadStringL(current_section, DBFILE_ENTRY_NAME, entry_name);
if (!entry_name.IsEmpty())
{
unsigned entry_name_length = entry_name.Length();
entry_name_str = entry_name.CStr();
unsigned long readpos;
BOOL warning;
buf.ExpandL(entry_name_length / 4*3);
OP_ASSERT((entry_name_length & 0x3) == 0);//multiple of four, else file is bogus
entry_name_length = (entry_name_length / 4) * 4;
make_singlebyte_in_place((char*)entry_name_str);
unsigned new_size_name = GeneralDecodeBase64((const unsigned char*)entry_name_str,
entry_name_length, readpos, (unsigned char*)buf.GetStorage(), warning, 0, NULL, NULL);
OP_ASSERT(!warning);
OP_ASSERT((unsigned)entry_name_length <= readpos);
OP_ASSERT((new_size_name & 0x1) == 0);
entry_name_length = new_size_name / 2;
// This copy is safe. entry_name is holding the b64 string which is 33% bigger.
op_memcpy(entry_name.CStr(), buf.GetStorage(), new_size_name);
entry_name.CStr()[entry_name_length] = 0;
}
else
{
entry_name_str = UNI_L("");
}
}
entry_db_version_str = NULL;
if (prefs_file.IsKey(current_section.CStr(), DBFILE_ENTRY_VERSION))
{
prefs_file.ReadStringL(current_section, DBFILE_ENTRY_VERSION, entry_db_version);
if (!entry_db_version.IsEmpty())
{
unsigned entry_db_version_length = entry_db_version.Length();
entry_db_version_str = entry_db_version.CStr();
unsigned long readpos;
BOOL warning;
buf.ExpandL(entry_db_version_length / 4 * 3);
OP_ASSERT((entry_db_version_length & 0x3) == 0);//multiple of four, else file is bogus
entry_db_version_length = (entry_db_version_length / 4) * 4;
make_singlebyte_in_place((char*)entry_db_version_str);
unsigned new_size_db_version = GeneralDecodeBase64((const unsigned char*)entry_db_version_str,
entry_db_version_length, readpos, (unsigned char*)buf.GetStorage(), warning, 0, NULL, NULL);
OP_ASSERT(!warning);
OP_ASSERT((unsigned)entry_db_version_length <= readpos);
OP_ASSERT((new_size_db_version & 0x1) == 0);
entry_db_version_length = new_size_db_version / 2;
// This copy is safe. entry_db_version is holding the b64 string which is 33% bigger.
op_memcpy(entry_db_version.CStr(), buf.GetStorage(), new_size_db_version);
entry_db_version.CStr()[entry_db_version_length] = 0;
}
else
{
entry_db_version_str = UNI_L("");
}
}
LEAVE_IF_ERROR(MakeIndex(FALSE, context_id));
PS_IndexEntry *key;
status = StoreObject(entry_type_number, entry_origin.CStr(),
entry_name_str, entry_datafile.CStr(),
entry_db_version_str, TRUE, context_id, &key);
LEAVE_IF_ERROR(status);
OP_ASSERT(key != NULL);
OP_ASSERT(CheckObjectExists(entry_type_number, entry_origin.CStr(),
entry_name_str, TRUE, context_id) == key);
// Update first file name number counter.
ParseFileNameNumber(context_id, entry_datafile.CStr());
if (entry_origin.Compare("opera:blank") == 0)
{
//delete opera:blank dbs -> these are generated for non-html docs
//but were leftover from previous versions
key->DeleteDataFile();
key->SetFlag(PS_IndexEntry::MARKED_FOR_DELETION | PS_IndexEntry::MEMORY_ONLY_DB);
}
}
}
static void MakeSHAInBuffer(CryptoHash* sha1_maker, TempBuffer& buffer)
{
if (sha1_maker == NULL) //if oom, just continue gracefully
return;
const uni_char *hex_digits = UNI_L("0123456789ABCDEF");
unsigned hash_size = sha1_maker->Size();
//make enough space
RETURN_VOID_IF_ERROR(buffer.Expand(hash_size * 2 + 1));
RETURN_VOID_IF_ERROR(sha1_maker->InitHash());
buffer.SetCachedLengthPolicy(TempBuffer::UNTRUSTED);
UINT8* data = reinterpret_cast<UINT8*>(buffer.GetStorage());
uni_char* string = buffer.GetStorage();
sha1_maker->CalculateHash(data, UNICODE_SIZE(buffer.Length()));
sha1_maker->ExtractHash(data);
for(unsigned j = hash_size; j > 0; j--)
{
string[j * 2 - 1] = hex_digits[(data[j - 1] ) & 0xf];
string[j * 2 - 2] = hex_digits[(data[j - 1] >> 4) & 0xf];
}
string[hash_size * 2] = 0;
buffer.SetCachedLengthPolicy(TempBuffer::TRUSTED);
}
OP_STATUS PS_Manager::FlushIndexToFile(URL_CONTEXT_ID context_id)
{
TRAPD(status, {
FlushIndexToFileL(context_id);
});
return status;
}
void PS_Manager::FlushIndexToFileL(URL_CONTEXT_ID context_id)
{
#ifdef SELFTEST
if (m_self_test_instance) return;
#endif
if (context_id == DB_NULL_CONTEXT_ID)
{
if (m_object_index.GetCount() == 0)
return;
OpHashIterator* itr = m_object_index.GetIterator();
LEAVE_IF_NULL(itr);
OP_STATUS status = OpStatus::OK;
if (OpStatus::IsSuccess(itr->First()))
{
do {
URL_CONTEXT_ID ctx_id = reinterpret_cast<URL_CONTEXT_ID>(itr->GetKey());
OP_ASSERT(ctx_id != DB_NULL_CONTEXT_ID);
status = OpDbUtils::GetOpStatusError(FlushIndexToFile(ctx_id), status);
} while (OpStatus::IsSuccess(itr->Next()));
}
OP_DELETE(itr);
LEAVE_IF_ERROR(status);
return;
}
if (!IsInitialized())
return;
IndexByContext* mgr_data = GetIndex(context_id);
if (mgr_data == NULL || mgr_data->GetIsFlushing() || !mgr_data->WasRegistered() || !mgr_data->HasReadFile())
return;
mgr_data->SetIsFlushing(TRUE);
IndexByContext::UnsetFlushHelper mgr_data_unset(mgr_data);
ANCHOR(IndexByContext::UnsetFlushHelper, mgr_data_unset);
DB_DBG(("Flushing index %d, %S\n", context_id, mgr_data->GetFileFd().GetFullPath()))
PrefsFile prefs_file(PREFS_XML);
ANCHOR(PrefsFile, prefs_file);
prefs_file.ConstructL();
prefs_file.SetFileL(&mgr_data->GetFileFd());
OpStackAutoPtr<PS_IndexIterator> iterator(GetIteratorL(context_id, KDBTypeStart));
OP_ASSERT(iterator.get());
if (!iterator->AtEndL())
{
CryptoHash* sha1_maker = CryptoHash::CreateSHA1();
OpStackAutoPtr<CryptoHash> sha1_maker_ptr(sha1_maker);
TempBuffer& buf = GetTempBuffer();
TempBuffer b64buf;
ANCHOR(TempBuffer, b64buf);
PS_IndexEntry *key;
while(!iterator->AtEndL())
{
key = iterator->GetItemL();
OP_ASSERT(key != NULL);
// During shutdown, the objects must be pre-deleted, else
// this assert triggers, which means that DropEntireIndex()
// is not traversing all objects.
OP_ASSERT(key->GetPSManager()->IsOperaRunning() || key->GetObject() == NULL);
//skip entries without file IF they are not going to be deleted
if (!key->HasWritableData() && !key->GetFlag(PS_IndexEntry::MARKED_FOR_DELETION))
{
iterator->MoveNextL();
continue;
}
//skip entries with bogus file
if (key->GetFileNameObj() != NULL && key->GetFileNameObj()->IsBogus())
{
iterator->MoveNextL();
continue;
}
//key -> ps_obj type origin name
buf.Clear();
buf.AppendL(GetTypeDesc(key->GetType()));
if (key->GetOrigin() != NULL)
{
buf.AppendL(' ');
buf.AppendL(key->GetOrigin());
}
if (key->GetName() != NULL)
{
buf.AppendL(' ');
buf.AppendL(key->GetName());
}
if (key->GetFlag(PS_IndexEntry::MARKED_FOR_DELETION))
{
prefs_file.DeleteSectionL(buf.GetStorage());
MakeSHAInBuffer(sha1_maker, buf);
prefs_file.DeleteSectionL(buf.GetStorage());
if (key->GetFlag(PS_IndexEntry::PURGE_ENTRY) &&
!IsBeingDestroyed())
{
key->UnsetFlag(PS_IndexEntry::MARKED_FOR_DELETION);
DeleteEntryNow(key->GetType(), key->GetOrigin(), key->GetName(),
!key->IsMemoryOnly(), key->GetUrlContextId());
iterator->ReSync();
continue;
}
}
else
{
prefs_file.DeleteSectionL(buf.GetStorage());
MakeSHAInBuffer(sha1_maker, buf);
prefs_file.WriteStringL(buf.GetStorage(), DBFILE_ENTRY_TYPE, key->GetTypeDesc());
if (key->GetOrigin() != NULL)
prefs_file.WriteStringL(buf.GetStorage(), DBFILE_ENTRY_ORIGIN, key->GetOrigin());
prefs_file.WriteStringL(buf.GetStorage(), DBFILE_ENTRY_FILE, key->GetFileRelPath());
//the following two are specified by webpages, so there should be escaped
if (key->GetName() != NULL)
{
unsigned bsize = UNICODE_SIZE(uni_strlen(key->GetName()));
b64buf.ExpandL((bsize + 2) / 3 * 4 + 1);
char *b64 = NULL;
int b64sz = 0;
switch (MIME_Encode_SetStr(b64, b64sz, (const char*)key->GetName(),
bsize, NULL, GEN_BASE64_ONELINE))
{
case MIME_NO_ERROR:
break;
case MIME_FAILURE:
LEAVE(OpStatus::ERR_NO_MEMORY);
break;
default:
LEAVE(OpStatus::ERR);
}
OP_ASSERT((unsigned)b64sz <= b64buf.GetCapacity());
b64buf.ExpandL(b64sz + 1);
make_doublebyte_in_buffer(b64, b64sz, b64buf.GetStorage(), b64sz + 1);
OP_DELETEA(b64);
prefs_file.WriteStringL(buf.GetStorage(), DBFILE_ENTRY_NAME, b64buf.GetStorage());
b64buf.Clear();
}
else
{
prefs_file.DeleteKeyL(buf.GetStorage(), DBFILE_ENTRY_NAME);
}
if (key->GetVersion() != NULL)
{
unsigned bsize = UNICODE_SIZE(uni_strlen(key->GetVersion()));
b64buf.ExpandL((bsize + 2) / 3 * 4 + 1);
char *b64 = NULL;
int b64sz = 0;
switch (MIME_Encode_SetStr(b64, b64sz, (const char*)key->m_db_version,
bsize, NULL, GEN_BASE64_ONELINE))
{
case MIME_NO_ERROR:
break;
case MIME_FAILURE:
LEAVE(OpStatus::ERR_NO_MEMORY);
break;
default:
LEAVE(OpStatus::ERR);
}
OP_ASSERT((unsigned)b64sz <= b64buf.GetCapacity());
b64buf.ExpandL(b64sz + 1);
make_doublebyte_in_buffer(b64, b64sz, b64buf.GetStorage(), b64sz + 1);
OP_DELETEA(b64);
prefs_file.WriteStringL(buf.GetStorage(), DBFILE_ENTRY_VERSION, b64buf.GetStorage());
b64buf.Clear();
}
else
{
prefs_file.DeleteKeyL(buf.GetStorage(), DBFILE_ENTRY_VERSION);
}
}
iterator->MoveNextL();
}
}
prefs_file.CommitL(TRUE, TRUE);
m_last_save_mod_counter = m_modification_counter;
}
OP_STATUS PS_Manager::FlushIndexToFileAsync(URL_CONTEXT_ID context_id)
{
#ifdef SELFTEST
if (m_self_test_instance)
return OpStatus::OK;
#endif //SELFTEST
BOOL has_posted_msg = GetIndex(context_id) != NULL && GetIndex(context_id)->HasPostedFlushMessage();
if (!IsInitialized() || has_posted_msg || GetMessageHandler() == NULL)
return OpStatus::OK;
if (GetMessageHandler()->PostMessage(MSG_DB_MANAGER_FLUSH_INDEX_ASYNC,
GetMessageQueueId(), context_id, 0))
{
if (GetIndex(context_id) != NULL)
GetIndex(context_id)->SetPostedFlushMessage();
return OpStatus::OK;
}
else
return OpStatus::ERR_NO_MEMORY;
}
PS_IndexIterator*
PS_Manager::GetIteratorL(URL_CONTEXT_ID context_id, PS_ObjectType use_case_type,
const uni_char* origin, BOOL only_persistent, PS_IndexIterator::IterationOrder order)
{
LEAVE_IF_ERROR(EnsureInitialization());
LEAVE_IF_ERROR(MakeIndex(TRUE, context_id));
OP_ASSERT(NULL != GetIndex(context_id));
OpStackAutoPtr<PS_IndexIterator> itr_ptr(OP_NEW_L(PS_IndexIterator, (this, context_id, use_case_type, origin, only_persistent, order)));
itr_ptr->BuildL();
return itr_ptr.release();
}
OP_STATUS
PS_Manager::EnumerateContextIds(PS_MgrContentIterator* enumerator)
{
DB_ASSERT_RET(enumerator != NULL, OpStatus::ERR_OUT_OF_RANGE);
if (m_object_index.GetCount() == 0)
return OpStatus::OK;
class ThisItr: public OpHashTableForEachListener {
public:
PS_MgrContentIterator *m_enumerator;
OP_STATUS m_status;
ThisItr(PS_MgrContentIterator *enumerator) : m_enumerator(enumerator), m_status(OpStatus::OK){}
virtual void HandleKeyData(const void* key, void* data)
{
IndexByContext * ctx = static_cast<IndexByContext* >(data);
if (!ctx->WasRegistered())
// Context not registered therefore should not be enumerated.
return;
URL_CONTEXT_ID ctx_id = reinterpret_cast<URL_CONTEXT_ID>(key);
OP_ASSERT(ctx_id != DB_NULL_CONTEXT_ID);
m_status = OpDbUtils::GetOpStatusError(m_status, m_enumerator->HandleContextId(ctx_id));
}
} itr(enumerator);
m_inside_enumerate_count++;
m_object_index.ForEach(&itr);
m_inside_enumerate_count--;
return itr.m_status;
}
OP_STATUS
PS_Manager::EnumerateTypes(PS_MgrContentIterator* enumerator, URL_CONTEXT_ID context_id)
{
DB_ASSERT_RET(enumerator != NULL && context_id != DB_NULL_CONTEXT_ID, OpStatus::ERR_OUT_OF_RANGE);
RETURN_IF_ERROR(EnsureInitialization());
RETURN_IF_ERROR(MakeIndex(TRUE, context_id));
IndexByContext* object_index = GetIndex(context_id);
OP_STATUS status = OpStatus::OK;
if (object_index != NULL)
{
m_inside_enumerate_count++;
union { int k; PS_ObjectType db_type; };
for (k = KDBTypeStart + 1; k < KDBTypeEnd; k++)
if (object_index->m_object_index[db_type] != NULL)
status = OpDbUtils::GetOpStatusError(status, enumerator->HandleType(context_id, db_type));
m_inside_enumerate_count--;
}
return status;
}
OP_STATUS
PS_Manager::EnumerateOrigins(PS_MgrContentIterator* enumerator, URL_CONTEXT_ID context_id, PS_ObjectType type)
{
DB_ASSERT_RET(enumerator != NULL &&
context_id != DB_NULL_CONTEXT_ID &&
ValidateObjectType(type), OpStatus::ERR_OUT_OF_RANGE);
RETURN_IF_ERROR(EnsureInitialization());
RETURN_IF_ERROR(MakeIndex(TRUE, context_id));
IndexByContext* object_index = GetIndex(context_id);
if (object_index != NULL)
{
IndexEntryByOriginHash** origin_table = object_index->m_object_index[type];
if (origin_table != NULL)
{
class ThisItr : public OpHashTableForEachListener {
public:
PS_MgrContentIterator *m_enumerator;
OP_STATUS m_status;
URL_CONTEXT_ID m_context_id;
PS_ObjectType m_type;
ThisItr(PS_MgrContentIterator *enumerator, PS_ObjectType type, URL_CONTEXT_ID context_id) :
m_enumerator(enumerator), m_status(OpStatus::OK), m_context_id(context_id), m_type(type) {}
virtual void HandleKeyData(const void* key, void* data){
const uni_char* origin = reinterpret_cast<const uni_char*>(key);
m_status = OpDbUtils::GetOpStatusError(m_status,
m_enumerator->HandleOrigin(m_context_id, m_type, origin));
}
} itr(enumerator, type, context_id);
m_inside_enumerate_count++;
for(unsigned k = 0; k < m_max_hash_amount; k++)
{
if (origin_table[k] != NULL)
origin_table[k]->m_origin_cached_info.ForEach(&itr);
}
m_inside_enumerate_count--;
return itr.m_status;
}
}
return OpStatus::OK;
}
OP_STATUS
PS_Manager::EnumerateObjects(PS_MgrContentIterator* enumerator,
URL_CONTEXT_ID context_id, PS_ObjectType type, const uni_char* origin)
{
DB_ASSERT_RET(enumerator != NULL &&
origin != NULL && origin[0] != 0 &&
context_id != DB_NULL_CONTEXT_ID &&
ValidateObjectType(type), OpStatus::ERR_OUT_OF_RANGE);
RETURN_IF_ERROR(EnsureInitialization());
RETURN_IF_ERROR(MakeIndex(TRUE, context_id));
IndexByContext* object_index = GetIndex(context_id);
if (object_index != NULL)
{
IndexEntryByOriginHash** origins_table = object_index->m_object_index[type];
if (origins_table != NULL)
{
IndexEntryByOriginHash* origins_hm = origins_table[HashOrigin(origin)];
if (origins_hm)
{
m_inside_enumerate_count++;
for (unsigned k = 0, m = origins_hm->m_objects.GetCount(); k < m; k++)
{
PS_IndexEntry *entry = origins_hm->m_objects.Get(k);
if (uni_str_eq(entry->GetOrigin(), origin))
{
enumerator->HandleObject(entry);
}
}
m_inside_enumerate_count--;
}
}
}
return OpStatus::OK;
}
PS_IndexEntry* PS_Manager::CheckObjectExists(PS_ObjectType type,
const uni_char* origin, const uni_char* name,
BOOL is_persistent, URL_CONTEXT_ID context_id) const
{
DB_ASSERT_RET(IsInitialized() && ValidateObjectType(type), NULL);
RETURN_VALUE_IF_ERROR(CheckOrigin(type, origin, is_persistent), NULL);
IndexByContext* object_index = GetIndex(context_id);
if (object_index != NULL)
{
IndexEntryByOriginHash** origin_table = object_index->m_object_index[type];
if (origin_table != NULL)
{
unsigned hashed_origin = HashOrigin(origin);
OP_ASSERT(hashed_origin < m_max_hash_amount);
IndexEntryByOriginHash* key_table = origin_table[hashed_origin];
if (key_table != NULL)
{
UINT32 index, limit = key_table->m_objects.GetCount();
for(index = 0; index < limit; index++)
{
PS_IndexEntry *object_index = key_table->m_objects.Get(index);
OP_ASSERT(object_index != NULL);//vector cannot have empty items
if (object_index &&
object_index->IsEqual(type, origin, name, is_persistent, context_id))
return object_index;
}
}
}
}
return NULL;
}
unsigned PS_Manager::GetNumberOfObjects(URL_CONTEXT_ID context_id, PS_ObjectType type, const uni_char* origin) const
{
IndexEntryByOriginHash *ci = GetIndexEntryByOriginHash(context_id, type, origin);
return ci != NULL ? ci->GetNumberOfDbs(origin): 0;
}
OP_STATUS PS_Manager::StoreObject(PS_ObjectType type, const uni_char* origin,
const uni_char* name, const uni_char* data_file_name,
const uni_char* db_version, BOOL is_persistent, URL_CONTEXT_ID context_id,
PS_IndexEntry** created_entry)
{
DB_ASSERT_RET(IsInitialized() && ValidateObjectType(type) && m_inside_enumerate_count == 0, PS_Status::ERR_INVALID_STATE);
//OP_ASSERT this should not exist in our builds !
PS_IndexEntry* key = CheckObjectExists(type, origin, name, is_persistent, context_id);
OP_ASSERT(key == NULL);
if (key != NULL)
{
//we can't have entries being rewritten so ignore duplicate entries
//in case some user feels like fiddling with the index file
if (created_entry != NULL)
*created_entry = key;
return OpStatus::OK;
}
//sanity checks
OP_ASSERT(is_persistent || data_file_name == NULL || uni_str_eq(g_ps_memory_file_name, data_file_name));
//the callee must have initialized it !
IndexByContext* mgr_data = GetIndex(context_id);
OP_ASSERT(mgr_data != NULL);
IndexEntryByOriginHash** origin_table = NULL;
if (mgr_data->m_object_index[type] == NULL)
{
RETURN_OOM_IF_NULL(origin_table = OP_NEWA(IndexEntryByOriginHash*, m_max_hash_amount));
op_memset(origin_table, 0, sizeof(IndexEntryByOriginHash*)*m_max_hash_amount);
mgr_data->m_object_index[type] = origin_table;
}
else
{
origin_table = mgr_data->m_object_index[type];
}
OP_ASSERT(origin_table != NULL);
unsigned hashed_origin = HashOrigin(origin);
OP_ASSERT(hashed_origin < m_max_hash_amount);
IndexEntryByOriginHash* key_table = NULL;
if (origin_table[hashed_origin] == NULL)
{
RETURN_OOM_IF_NULL(key_table = OP_NEW(IndexEntryByOriginHash, ()));
origin_table[hashed_origin] = key_table;
}
else
{
key_table = origin_table[hashed_origin];
}
OP_STATUS status;
PS_IndexEntry *datafile_entry = PS_IndexEntry::Create(this, context_id,
type, origin, name, data_file_name, db_version, is_persistent, NULL);
if (datafile_entry != NULL)
{
if (OpStatus::IsSuccess(status = key_table->m_objects.Add(datafile_entry)))
{
if (OpStatus::IsSuccess(status = key_table->IncNumberOfDbs(origin)))
{
//Success !
if (created_entry != NULL)
*created_entry = datafile_entry;
m_modification_counter++;
return OpStatus::OK;
}
key_table->m_objects.Remove(key_table->m_objects.GetCount() - 1);
}
OP_DELETE(datafile_entry);
}
else
status = OpStatus::ERR_NO_MEMORY;
if (origin_table[hashed_origin] &&
origin_table[hashed_origin]->m_objects.GetCount() == 0)
{
OP_DELETE(origin_table[hashed_origin]);
origin_table[hashed_origin] = NULL;
}
OP_ASSERT(origin_table[hashed_origin] == NULL || origin_table[hashed_origin]->m_objects.GetCount() != 0);
return status;
}
BOOL PS_Manager::DeleteEntryNow(PS_ObjectType type,
const uni_char* origin, const uni_char* name,
BOOL is_persistent, URL_CONTEXT_ID context_id)
{
DB_ASSERT_RET(IsInitialized() && ValidateObjectType(type) && m_inside_enumerate_count == 0, FALSE);
RETURN_VALUE_IF_ERROR(CheckOrigin(type, origin, is_persistent), FALSE);
BOOL found_something = FALSE;
//although the asserts validates the types, release builds don't have asserts
//which could cause data to be written in places it shouldn't
OP_ASSERT(ValidateObjectType(type));
if (!ValidateObjectType(type))
return found_something;
IndexByContext* mgr_data = GetIndex(context_id);
if (mgr_data != NULL)
{
IndexEntryByOriginHash** origin_table = mgr_data->m_object_index[type];
if (origin_table != NULL)
{
unsigned hashed_origin = HashOrigin(origin);
OP_ASSERT(hashed_origin < m_max_hash_amount);
IndexEntryByOriginHash* key_table = origin_table[hashed_origin];
if (key_table != NULL)
{
UINT32 index, limit = key_table->m_objects.GetCount();
for(index = 0; index < limit; index++)
{
PS_IndexEntry *object_index = key_table->m_objects.Get(index);
OP_ASSERT(object_index != NULL); // Vector cannot have empty items.
if (object_index &&
object_index->IsEqual(type, origin, name, is_persistent, context_id))
{
if (object_index->GetFlag(PS_IndexEntry::BEING_DELETED))
{
if (!object_index->IsMemoryOnly() && object_index->GetFlag(PS_IndexEntry::MARKED_FOR_DELETION))
{
OpStatus::Ignore(FlushIndexToFile(object_index->GetUrlContextId()));
}
}
else
{
if (!object_index->IsMemoryOnly() && object_index->GetFlag(PS_IndexEntry::MARKED_FOR_DELETION))
{
OpStatus::Ignore(FlushIndexToFileAsync(object_index->GetUrlContextId()));
}
else
{
#ifdef DATABASE_MODULE_DEBUG
dbg_printf("Deleting ps_obj (%d,%S,%S,%s)\n", type,
origin, name, is_persistent ? "persistent" : "memory");
#endif //DATABASE_MODULE_DEBUG
key_table->m_objects.Remove(index--);
key_table->DecNumberOfDbs(origin);
OP_DELETE(object_index);
m_modification_counter++;
}
}
found_something = TRUE;
break;
}
}
if (origin_table[hashed_origin] &&
origin_table[hashed_origin]->m_objects.GetCount() == 0)
{
OP_DELETE(origin_table[hashed_origin]);
origin_table[hashed_origin] = NULL;
}
}
}
}
return found_something;
}
PS_Manager::IndexByContext::IndexByContext(PS_Manager* mgr, URL_CONTEXT_ID context_id)
: m_mgr(mgr)
, m_context_id(context_id)
, m_context_folder_id(OPFILE_ABSOLUTE_FOLDER)
, m_bools_init(0)
{
OP_ASSERT(mgr != NULL);
op_memset(m_object_index, 0, sizeof(m_object_index));
for(unsigned k = 0; k < DATABASE_INDEX_LENGTH; k++)
m_cached_data_size[k] = FILE_LENGTH_NONE;
}
PS_Manager::IndexByContext::~IndexByContext()
{
m_bools.being_deleted = TRUE;
for (unsigned k = 0; k < DATABASE_INDEX_LENGTH; k++)
{
if (m_object_index[k] != NULL)
{
for (unsigned m = 0; m < m_max_hash_amount; m++)
{
if (m_object_index[k][m] != NULL)
{
OP_DELETE(m_object_index[k][m]);
m_object_index[k][m] = NULL;
}
}
OP_DELETEA(m_object_index[k]);
m_object_index[k] = NULL;
}
}
}
PS_Manager::IndexEntryByOriginHash*
PS_Manager::IndexByContext::GetIndexEntryByOriginHash(PS_ObjectTypes::PS_ObjectType type, const uni_char* origin) const
{
return m_object_index[type] != NULL && origin != NULL ? m_object_index[type][HashOrigin(origin)] : NULL;
}
OP_STATUS
PS_Manager::IndexByContext::InitializeFile()
{
if (HasReadFile())
return OpStatus::OK;
PS_Policy* def_policy = g_database_policies->GetPolicy(PS_ObjectTypes::KDBTypeStart);
OP_ASSERT(def_policy != NULL);
TempBuffer &buf = m_mgr->GetTempBuffer(TRUE);
const uni_char *profile_folder = def_policy->GetAttribute(PS_Policy::KMainFolderPath, m_context_id);
RETURN_OOM_IF_NULL(profile_folder);
if (*profile_folder == 0)
return OpStatus::ERR_NO_ACCESS;
RETURN_IF_ERROR(buf.Append(profile_folder));
ENSURE_PATHSEPCHAR(buf);
RETURN_IF_ERROR(buf.Append(def_policy->GetAttribute(PS_Policy::KSubFolder, m_context_id)));
ENSURE_PATHSEPCHAR(buf);
RETURN_IF_ERROR(buf.Append(DATABASE_INTERNAL_PERSISTENT_INDEX_FILENAME));
RETURN_IF_ERROR(m_index_file_fd.Construct(buf.GetStorage()));
#ifdef DATABASE_MODULE_DEBUG
dbg_printf("Reading ps_obj index: %d %S\n", m_context_id, m_index_file_fd.GetFullPath());
#endif // DATABASE_MODULE_DEBUG
TRAPD(status,m_mgr->ReadIndexFromFileL(m_index_file_fd, m_context_id));
if (OpStatus::IsSuccess(status))
m_bools.file_was_read = true;
#ifdef DATABASE_MODULE_DEBUG
dbg_printf(" - %d\n", status);
TRAPD(________status,m_mgr->DumpIndexL(m_context_id, UNI_L("After loading")));
#endif // DATABASE_MODULE_DEBUG
return status;
}
OP_STATUS PS_Manager::MakeIndex(BOOL load_file, URL_CONTEXT_ID context_id)
{
IndexByContext* index = GetIndex(context_id);
if (index == NULL)
{
index = OP_NEW(IndexByContext, (this, context_id));
RETURN_OOM_IF_NULL(index);
OP_STATUS status = m_object_index.Add(INT_TO_PTR(context_id), index);
if (OpStatus::IsError(status))
{
OP_DELETE(index);
return status;
}
}
if (load_file && index->WasRegistered())
{
OP_ASSERT(IsInitialized());
RETURN_IF_MEMORY_ERROR(index->InitializeFile());
}
return OpStatus::OK;
}
PS_Manager::IndexEntryByOriginHash*
PS_Manager::GetIndexEntryByOriginHash(URL_CONTEXT_ID context_id, PS_ObjectTypes::PS_ObjectType type, const uni_char* origin) const
{
if (origin == NULL || origin[0] == 0)
return NULL;
IndexByContext* index = GetIndex(context_id);
return index != NULL ? index->GetIndexEntryByOriginHash(type, origin) : NULL;
}
void
PS_Manager::DropEntireIndex(URL_CONTEXT_ID context_id)
{
if (!IsInitialized())
return;
/**
* First we explicitly delete only the ps_obj objects.
* Some will flush data and the index to disk for instance,
* so we should ensure that the index is intact while the
* ps_obj objects are deleted, else the iterators become
* invalid and may crash
*/
struct DbItr : public PS_MgrContentIterator
{
DbItr(PS_Manager* mgr) : m_mgr(mgr) {}
virtual OP_STATUS HandleContextId(URL_CONTEXT_ID context_id)
{
PS_Manager::IndexByContext *ctx = m_mgr->GetIndex(context_id);
if (ctx->HasReadFile())
{
ctx->SetIndexBeingDeleted();
return m_mgr->EnumerateTypes(this, context_id);
}
else
return OpStatus::OK;
}
virtual OP_STATUS HandleType(URL_CONTEXT_ID context_id, PS_ObjectType type)
{
return m_mgr->EnumerateOrigins(this, context_id, type);
}
virtual OP_STATUS HandleOrigin(URL_CONTEXT_ID context_id, PS_ObjectType type, const uni_char* origin)
{
return m_mgr->EnumerateObjects(this, context_id, type, origin);
}
virtual OP_STATUS HandleObject(PS_IndexEntry* object_key)
{
if (object_key->GetObject() != NULL)
{
INTEGRITY_CHECK_P(object_key->GetObject());
OP_ASSERT(m_dbs.Find(object_key->GetObject()) == -1);
RETURN_IF_ERROR(m_dbs.Add(object_key->GetObject()));
}
return OpStatus::OK;
}
PS_Manager* m_mgr;
OpVector<PS_Object> m_dbs;
} delete_enumerator(this);
if (context_id != DB_NULL_CONTEXT_ID)
{
PS_Manager::IndexByContext *ctx = GetIndex(context_id);
if (ctx != NULL && ctx->HasReadFile())
ctx->SetIndexBeingDeleted();
else
return;
}
OP_STATUS status = OpStatus::OK;
do {
//loop ensures that everything is cleanup even if there is OOM
//while populating the OpVector
if (context_id == DB_NULL_CONTEXT_ID)
status = EnumerateContextIds(&delete_enumerator);
else
status = EnumerateTypes(&delete_enumerator, context_id);
if (delete_enumerator.m_dbs.GetCount() == 0)
break;
for(int k = delete_enumerator.m_dbs.GetCount() - 1; k >= 0; k--)
{
PS_Object *o = delete_enumerator.m_dbs.Get(k);
INTEGRITY_CHECK_P(o);
OP_ASSERT(delete_enumerator.m_dbs.Find(o) == k);
OP_DELETE(o);
}
delete_enumerator.m_dbs.Empty();
} while(OpStatus::IsMemoryError(status));
ReportCondition(status);
OpStatus::Ignore(FlushIndexToFile(context_id));
if (context_id != DB_NULL_CONTEXT_ID)
{
IndexByContext* index = NULL;
if (OpStatus::IsSuccess(m_object_index.Remove(INT_TO_PTR(context_id), &index)))
OP_DELETE(index);
}
}
unsigned
PS_Manager::HashOrigin(const uni_char* origin)
{
unsigned calc_hash = 0;
if (origin != NULL)
{
for(unsigned idx = 0; idx < m_max_hash_chars && origin[idx] != 0; idx++)
{
calc_hash = calc_hash ^ origin[idx];
}
}
return calc_hash & m_hash_mask;
}
const uni_char* PS_Manager::GetTypeDesc(PS_ObjectType type) const {
//although the asserts validates the types, release builds don't have asserts
//which could cause data to be written in places it shouldn't
OP_ASSERT(ValidateObjectType(type));
if (!ValidateObjectType(type))
return NULL;
return database_module_mgr_psobj_types[type];
}
PS_ObjectTypes::PS_ObjectType PS_Manager::GetDescType(const uni_char* desc) const
{
union { PS_ObjectType type; int x; };
type = KDBTypeStart;
if (desc != NULL) {
for (unsigned idx = KDBTypeStart + 1; idx < KDBTypeEnd && database_module_mgr_psobj_types[idx] != NULL; idx++)
{
if (desc == database_module_mgr_psobj_types[idx] ||
uni_str_eq(desc, database_module_mgr_psobj_types[idx]))
{
x = idx;
break;
}
}
}
OP_ASSERT(KDBTypeStart <= type && type < KDBTypeEnd);
return type;
}
/*static*/ PS_Manager::DeleteDataInfo*
PS_Manager::DeleteDataInfo::Create(URL_CONTEXT_ID context_id, unsigned type_flags, bool is_extension, const uni_char* origin)
{
void *p = op_malloc(sizeof(DeleteDataInfo) + (origin ? UNICODE_SIZE(uni_strlen(origin)) : 0));
RETURN_VALUE_IF_NULL(p, NULL);
DeleteDataInfo *o = new (p) DeleteDataInfo();
if (origin != NULL)
uni_strcpy(o->m_origin, origin);
else
o->m_origin[0] = 0;
o->m_context_id = context_id;
o->m_type_flags = type_flags;
#ifdef EXTENSION_SUPPORT
o->m_is_extension = is_extension;
#endif // EXTENSION_SUPPORT
return o;
}
void
PS_Manager::PostDeleteDataMessage(URL_CONTEXT_ID context_id, unsigned type_flags, const uni_char* origin, bool is_extension)
{
if (type_flags && GetMessageHandler() != NULL)
{
OP_STATUS status = EnsureInitialization();
if (OpStatus::IsError(status))
ReportCondition(status);
else
{
DeleteDataInfo* o = DeleteDataInfo::Create(context_id, type_flags, is_extension, origin);
if (o == NULL)
ReportCondition(OpStatus::ERR_NO_MEMORY);
else
{
o->Into(&m_to_delete);
if (!GetMessageHandler()->PostMessage(MSG_DB_MODULE_DELAYED_DELETE_DATA, GetMessageQueueId(), 0, 0))
ReportCondition(OpStatus::ERR_NO_MEMORY);
}
}
}
}
void
PS_Manager::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
OP_ASSERT(par1 == GetMessageQueueId());
switch(msg)
{
case MSG_DB_MANAGER_FLUSH_INDEX_ASYNC:
{
//during module destruction messages are no longer flushed
IndexByContext* index = GetIndex(static_cast<URL_CONTEXT_ID>(par2));
if (index != NULL)
index->UnsetPostedFlushMessage();
ReportCondition(FlushIndexToFile(static_cast<URL_CONTEXT_ID>(par2)));
break;
}
case MSG_DB_MODULE_DELAYED_DELETE_DATA:
{
ReportCondition(FlushDeleteQueue(TRUE));
break;
}
default:
OP_ASSERT(!"Warning: unhandled message received");
}
}
OP_STATUS PS_Manager::FlushDeleteQueue(BOOL apply)
{
if (!apply)
{
DeleteDataInfo* o;
while((o = m_to_delete.First()) != NULL)
{
o->Out();
op_free(o);
}
return OpStatus::OK;
}
class GetIdsItr : public PS_MgrContentIterator {
public:
GetIdsItr() : has_read_all(FALSE) {}
BOOL has_read_all;
OpINT32Set ids;
virtual OP_STATUS HandleContextId(URL_CONTEXT_ID context_id)
{
return ids.Add(static_cast<INT32>(context_id));
}
} ids;
class DeleteDataItr : public OpINT32Set::ForEachIterator {
public:
DeleteDataItr(PS_Manager *mgr)
: m_mgr(mgr)
, m_purge_orphans(false)
#ifdef EXTENSION_SUPPORT
, m_is_extension(false)
#endif // EXTENSION_SUPPORT
, m_status(OpStatus::OK) {}
PS_Manager *m_mgr;
bool m_purge_orphans;
#ifdef EXTENSION_SUPPORT
bool m_is_extension;
#endif // EXTENSION_SUPPORT
OP_STATUS m_status;
PS_ObjectType m_type;
const uni_char *m_origin;
virtual void HandleInteger(INT32 context_id)
{
if (m_purge_orphans)
m_status = OpDbUtils::GetOpStatusError(m_status, m_mgr->DeleteOrphanFiles(static_cast<URL_CONTEXT_ID>(context_id)));
else
{
if (IndexByContext *idx = m_mgr->GetIndex(static_cast<URL_CONTEXT_ID>(context_id)))
{
#ifdef EXTENSION_SUPPORT
if (idx->IsExtensionContext() != m_is_extension)
return;
#endif // EXTENSION_SUPPORT
m_status = OpDbUtils::GetOpStatusError(m_status, m_mgr->DeleteObjects(m_type, static_cast<URL_CONTEXT_ID>(context_id), m_origin, FALSE));
#if defined EXTENSION_SUPPORT && defined WEBSTORAGE_WIDGET_PREFS_SUPPORT
if (m_is_extension && m_type == KWidgetPreferences)
g_gadget_manager->OnExtensionStorageDataClear(context_id, OpGadget::PREFS_APPLY_DATA_CLEARED);
#endif // defined EXTENSION_SUPPORT && defined WEBSTORAGE_WIDGET_PREFS_SUPPORT
}
}
}
} deldata(this);
OP_STATUS status = OpStatus::OK;
for (DeleteDataInfo* o = m_to_delete.First(); o != NULL; o = o->Suc())
{
//to understand what this cycle is doing, check PersistentStorageCommander::*
for (unsigned k = KDBTypeStart + 1, mask = 1; k < KDBTypeEnd; k++, mask <<=1)
{
if (mask & o->m_type_flags)
{
deldata.m_type = static_cast<PS_ObjectType>(k);
deldata.m_origin = o->m_origin;
#ifdef EXTENSION_SUPPORT
deldata.m_is_extension = o->m_is_extension;
#endif // EXTENSION_SUPPORT
if (o->m_context_id == PersistentStorageCommander::ALL_CONTEXT_IDS)
{
if (!ids.has_read_all)
{
status = OpDbUtils::GetOpStatusError(status, EnumerateContextIds(&ids));
ids.has_read_all = TRUE;
}
ids.ids.ForEach(&deldata);
}
else
{
if (!ids.has_read_all)
status = OpDbUtils::GetOpStatusError(status, ids.ids.Add(o->m_context_id));
deldata.HandleInteger(static_cast<INT32>(o->m_context_id));
}
}
}
}
deldata.m_purge_orphans = TRUE;
ids.ids.ForEach(&deldata);
FlushDeleteQueue(FALSE);
return status;
}
static
OP_STATUS DeleteOrphanFilesAux(const uni_char *folder_path, unsigned base_folder_path_length,
unsigned depth, const OpConstStringHashSet &existing_file_set, BOOL &folder_is_empty)
{
OpFolderLister *lister;
RETURN_IF_ERROR(OpFolderLister::Create(&lister));
OpAutoPtr<OpFolderLister> lister_ptr(lister);
RETURN_IF_ERROR(lister->Construct(folder_path, UNI_L("*")));
OpString rel_name_nojournal;
folder_is_empty = TRUE;
while (lister->Next())
{
if (uni_str_eq(lister->GetFileName(), ".") ||
uni_str_eq(lister->GetFileName(), ".."))
continue;
if (depth == 0 && uni_str_eq(lister->GetFileName(), DATABASE_INTERNAL_PERSISTENT_INDEX_FILENAME))
{
folder_is_empty = FALSE;
continue;
}
if (lister->IsFolder())
{
BOOL sub_folder_is_empty = FALSE;
RETURN_IF_ERROR(DeleteOrphanFilesAux(lister->GetFullPath(), base_folder_path_length, depth + 1, existing_file_set, sub_folder_is_empty));
if (sub_folder_is_empty)
{
DB_DBG(("DELETING ORPHAN FOLDER: %S\n", lister->GetFullPath()));
OpFile orphan_folder;
RETURN_IF_MEMORY_ERROR(orphan_folder.Construct(lister->GetFullPath()));
RETURN_IF_MEMORY_ERROR(orphan_folder.Delete());
}
else
folder_is_empty = FALSE;
}
else
{
const uni_char *rel_name = lister->GetFullPath() + base_folder_path_length;
BOOL not_found = !existing_file_set.Contains(rel_name);
#ifdef SQLITE_SUPPORT
if (not_found)
{
// Check if this is a sqlite journal file and if so, strip the-journal suffix
// and check if the main file exists.
unsigned rel_name_length = uni_strlen(rel_name);
if (8 < rel_name_length && uni_str_eq(rel_name + rel_name_length - 8, "-journal"))
{
RETURN_IF_MEMORY_ERROR(rel_name_nojournal.Set(rel_name, rel_name_length - 8));
not_found = !existing_file_set.Contains(rel_name_nojournal.CStr());
}
}
#endif // SQLITE_SUPPORT
if (not_found)
{
DB_DBG(("DELETING ORPHAN FILE: %S\n", lister->GetFullPath()));
OpFile orphan_file;
RETURN_IF_MEMORY_ERROR(orphan_file.Construct(lister->GetFullPath()));
RETURN_IF_MEMORY_ERROR(orphan_file.Delete());
}
else
folder_is_empty = FALSE;
}
}
return OpStatus::OK;
}
OP_STATUS PS_Manager::DeleteOrphanFiles(URL_CONTEXT_ID context_id)
{
DB_DBG(("PS_Manager::DeleteOrphanFiles(%u)\n", context_id));
PS_Policy* def_policy = g_database_policies->GetPolicy(PS_ObjectTypes::KDBTypeStart);
OP_ASSERT(def_policy != NULL);
const uni_char* profile_folder = def_policy->GetAttribute(PS_Policy::KMainFolderPath, context_id);
RETURN_OOM_IF_NULL(profile_folder);
if (*profile_folder == 0)
return OpStatus::ERR_NO_ACCESS;
const uni_char* storage_folder = def_policy->GetAttribute(PS_Policy::KSubFolder, context_id);
OP_ASSERT(storage_folder && *storage_folder);
TempBuffer folder_path;
RETURN_IF_ERROR(folder_path.Append(profile_folder));
ENSURE_PATHSEPCHAR(folder_path);
unsigned base_folder_path_length = folder_path.Length();
RETURN_IF_ERROR(folder_path.Append(storage_folder));
class FileItr : public PS_MgrContentIterator {
public:
PS_Manager *m_mgr;
OpConstStringHashSet m_file_name_set;
FileItr(PS_Manager *mgr) : m_mgr(mgr){}
~FileItr() {}
virtual OP_STATUS HandleType(URL_CONTEXT_ID context_id, PS_ObjectType type) {
return m_mgr->EnumerateOrigins(this, context_id, type);
}
virtual OP_STATUS HandleOrigin(URL_CONTEXT_ID context_id, PS_ObjectType type, const uni_char* origin) {
return m_mgr->EnumerateObjects(this, context_id, type, origin);
}
virtual OP_STATUS HandleObject(PS_IndexEntry* object_entry) {
if (object_entry->IsPersistent() &&
object_entry->GetFileRelPath() != NULL &&
!OpDbUtils::IsFilePathAbsolute(object_entry->GetFileRelPath()))
{
RETURN_IF_MEMORY_ERROR(m_file_name_set.Add(object_entry->GetFileRelPath()));
}
return OpStatus::OK;
}
} itr(this);
RETURN_IF_ERROR(EnumerateTypes(&itr, context_id));
BOOL folder_is_empty; // This is unused.
// 1st arg, folder to search for. First calls searches the pstorage folder
// 2nd arg, length of full path of the profile folder incl leading slash, because the relative path names are relative to it
return DeleteOrphanFilesAux(folder_path.GetStorage(), base_folder_path_length, 0, itr.m_file_name_set, folder_is_empty);
}
void
PS_Manager::ParseFileNameNumber(URL_CONTEXT_ID context_id, const uni_char* filename)
{
if (filename == NULL)
return;
unsigned filename_length = uni_strlen(filename);
// Generated file names have format .*/xx/xx/xxxxxxxx.
// Everything else would therefore have been added manually
// to the index, so we ignore those. We only need to check
// for collisions against the files that have the proper format.
if (filename_length < 15)
return;
for(unsigned ofs = filename_length - 15, k = 0; k < 15; k++){
if (k == 0 || k == 3 || k == 6) {
if (filename[ofs + k] != PATHSEPCHAR)
return;
}
else {
if (!uni_isxdigit(filename[ofs + k]))
return;
}
}
unsigned type_nr = uni_strtoul(filename + filename_length - 14, NULL, 16);
unsigned hash_nr = uni_strtoul(filename + filename_length - 11, NULL, 16);
unsigned file_nr = uni_strtoul(filename + filename_length - 8, NULL, 16);
// Check if the numbers are out of range indexes.
if (PS_ObjectTypes::KDBTypeEnd <= type_nr || m_max_hash_amount <= hash_nr)
return;
// If checks exists because the file path might have been edited manually
// and therefore unsyched with the values that would have been generated.
if (IndexByContext* data_0 = GetIndex(context_id))
if (IndexEntryByOriginHash** data_1 = data_0->m_object_index[type_nr])
if (IndexEntryByOriginHash* data_2 = data_1[hash_nr])
if (data_2->m_highest_filename_number <= file_nr)
// Might rollover, but it's really not a problem.
data_2->m_highest_filename_number = file_nr + 1;
DB_DBG(("PS_Manager::ParseFileNameNumber(%S): (0x%x), (0x%x), (0x%x)\n", filename, type_nr, hash_nr, file_nr));
}
PS_Manager::IndexEntryByOriginHash::~IndexEntryByOriginHash()
{
m_objects.DeleteAll(); // To be safe
m_origin_cached_info.DeleteAll();
}
unsigned
PS_Manager::IndexEntryByOriginHash::GetNumberOfDbs(const uni_char* origin) const
{
OriginCachedInfo* ci = GetCachedEntry(origin);
if (ci != NULL)
{
return ci->m_number_of_dbs;
}
return 0;
}
void
PS_Manager::IndexEntryByOriginHash::DecNumberOfDbs(const uni_char* origin)
{
OP_ASSERT(GetNumberOfDbs(origin)>0 || !m_origin_cached_info.Contains(origin));
OriginCachedInfo* ci = GetCachedEntry(origin);
if (ci != NULL)
ci->m_number_of_dbs--;
}
OP_STATUS
PS_Manager::IndexEntryByOriginHash::SetNumberOfDbs(const uni_char* origin, unsigned number_of_dbs)
{
if (origin == NULL || origin[0] == 0) return OpStatus::OK;
OriginCachedInfo* ci;
RETURN_IF_ERROR(MakeCachedEntry(origin, &ci));
OP_ASSERT(ci != NULL);
ci->m_number_of_dbs = number_of_dbs;
return OpStatus::OK;
}
OP_STATUS
PS_Manager::IndexEntryByOriginHash::SetCachedDataSize(const uni_char* origin, OpFileLength new_size)
{
if (origin == NULL || origin[0] == 0) return OpStatus::OK;
OriginCachedInfo* ci;
RETURN_IF_ERROR(MakeCachedEntry(origin, &ci));
OP_ASSERT(ci != NULL);
ci->m_cached_data_size = new_size;
return OpStatus::OK;
}
void
PS_Manager::IndexEntryByOriginHash::UnsetCachedDataSize(const uni_char* origin)
{
OriginCachedInfo* ci = GetCachedEntry(origin);
if (ci != NULL)
{
ci->m_cached_data_size = FILE_LENGTH_NONE;
}
}
BOOL
PS_Manager::IndexEntryByOriginHash::HasCachedDataSize(const uni_char* origin) const
{
OriginCachedInfo* ci = GetCachedEntry(origin);
if (ci != NULL)
{
return ci->m_cached_data_size != FILE_LENGTH_NONE;
}
return FALSE;
}
OpFileLength
PS_Manager::IndexEntryByOriginHash::GetCachedDataSize(const uni_char* origin) const
{
OriginCachedInfo* ci = GetCachedEntry(origin);
if (ci != NULL)
{
return ci->m_cached_data_size;
}
return FILE_LENGTH_NONE;
}
PS_Manager::IndexEntryByOriginHash::OriginCachedInfo*
PS_Manager::IndexEntryByOriginHash::GetCachedEntry(const uni_char* origin) const
{
OriginCachedInfo* ci;
if (origin != NULL && origin[0] && OpStatus::IsSuccess(m_origin_cached_info.GetData(origin, &ci)))
return ci;
return NULL;
}
OP_STATUS
PS_Manager::IndexEntryByOriginHash::MakeCachedEntry(const uni_char* origin, OriginCachedInfo** ci)
{
if (origin != NULL && origin[0] && (*ci = GetCachedEntry(origin)) == NULL)
{
*ci = (OriginCachedInfo*) OP_NEWA(byte, (sizeof(OriginCachedInfo) + UNICODE_SIZE(uni_strlen(origin))));
RETURN_OOM_IF_NULL(*ci);
uni_strcpy((*ci)->m_origin, origin);
(*ci)->m_number_of_dbs = 0;
(*ci)->m_cached_data_size = FILE_LENGTH_NONE;
OP_STATUS status = m_origin_cached_info.Add((*ci)->m_origin, *ci);
if (OpStatus::IsError(status))
{
OP_DELETEA(*ci);
return status;
}
}
return OpStatus::OK;
}
#ifdef DATABASE_MODULE_DEBUG
void PS_Manager::DumpIndexL(URL_CONTEXT_ID context_id, const uni_char* msg)
{
if (!IsInitialized())
return;
if (context_id == DB_NULL_CONTEXT_ID && m_object_index.GetCount() != 0)
{
OpHashIterator* itr = m_object_index.GetIterator();
LEAVE_IF_NULL(itr);
OP_STATUS status = OpStatus::OK, status2 = OpStatus::OK;
if (OpStatus::IsSuccess(itr->First()))
{
do {
URL_CONTEXT_ID ctx_id = reinterpret_cast<URL_CONTEXT_ID>(itr->GetKey());
OP_ASSERT(ctx_id != DB_NULL_CONTEXT_ID);
TRAP(status2, DumpIndexL(ctx_id, msg));
status = OpDbUtils::GetOpStatusError(status, status2);
} while (OpStatus::IsSuccess(itr->Next()));
}
OP_DELETE(itr);
LEAVE_IF_ERROR(status);
return;
}
int output_index = 1;
PS_IndexIterator *itr = GetIteratorL(context_id, KDBTypeStart, FALSE, PS_IndexIterator::ORDERED_DESCENDING);
OP_ASSERT(itr != NULL);
dbg_printf("PS_Manager::DumpIndexL(%d, %S)\n", context_id, msg);
if (!itr->AtEndL())
{
do {
const PS_IndexEntry* key = itr->GetItemL();
OP_ASSERT(key);
dbg_printf(" Database %d\n", output_index++);
dbg_printf(" Ctx: %x\n", key->GetUrlContextId());
dbg_printf(" Type: %S\n", GetTypeDesc(key->GetType()));
dbg_printf(" Origin: %S\n", key->GetOrigin());
dbg_printf(" Domain: %S\n", key->GetDomain());
dbg_printf(" Name: %S\n", key->GetName());
dbg_printf(" Memory: %s\n", key->IsMemoryOnly()?"yes":"no");
dbg_printf(" File: %S\n", key->GetFileRelPath());
dbg_printf(" Path: %S\n", key->GetFileAbsPath());
dbg_printf(" Version: %S\n", key->GetVersion());
dbg_printf(" To del : %s\n", DB_DBG_BOOL(key->GetFlag(PS_IndexEntry::MARKED_FOR_DELETION)));
dbg_printf(" Has obj: %s\n", DB_DBG_BOOL(key->GetObject() != NULL));
dbg_printf("\n");
} while(itr->MoveNextL());
}
else
{
dbg_printf(" no items\n");
}
OP_DELETE(itr);
}
#endif //DATABASE_MODULE_DEBUG
PS_IndexEntry*
PS_IndexEntry::Create(PS_Manager* mgr, URL_CONTEXT_ID context_id,
PS_ObjectType type, const uni_char* origin,
const uni_char* name, const uni_char* data_file_name,
const uni_char* db_version, BOOL is_persistent,
PS_Object* ps_obj)
{
PS_IndexEntry* index = OP_NEW(PS_IndexEntry,(mgr));
RETURN_VALUE_IF_NULL(index, NULL);
ANCHOR_PTR(PS_IndexEntry, index);
index->m_type = type;
index->m_context_id = context_id;
#ifdef WEBSTORAGE_ENABLE_SIMPLE_BACKEND
# ifdef DEBUG_ENABLE_OPASSERT
if (type == KLocalStorage
|| type == KSessionStorage
# ifdef WEBSTORAGE_WIDGET_PREFS_SUPPORT
|| type == KWidgetPreferences
# endif //defined WEBSTORAGE_WIDGET_PREFS_SUPPORT
# ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
|| type == KUserJsStorage
# endif //WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
)
{
OP_ASSERT(name == NULL);
}
else
{
OP_ASSERT(name != NULL);
}
# endif // DEBUG_ENABLE_OPASSERT
#endif // WEBSTORAGE_ENABLE_SIMPLE_BACKEND
if (origin != NULL && origin[0])
{
index->m_origin = UniSetNewStr(origin);
RETURN_VALUE_IF_NULL(index->m_origin, NULL);
#if defined WEBSTORAGE_ENABLE_SIMPLE_BACKEND && defined WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
if (type != KUserJsStorage)
#endif // defined WEBSTORAGE_ENABLE_SIMPLE_BACKEND && defined WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
{
unsigned origin_length = uni_strlen(index->m_origin);
//parse domain
unsigned domain_start = 0, domain_end = origin_length, k = 0;
for(; k < origin_length; k++)
{
if (index->m_origin[k] == ':' &&
index->m_origin[k + 1] == '/')
{
do {
k++;
}
while (!op_isalnum(index->m_origin[k]) && k < origin_length);
if (k < origin_length)
domain_start = k;
break;
}
else if (!uni_isalpha(index->m_origin[k]))
// Found junk before finding ':/' so it's serverless.
break;
}
if (domain_start != 0)
{
for(; k < origin_length; k++)
if (index->m_origin[k] == ':' || index->m_origin[k] == '/')
{
domain_end = k;
break;
}
domain_end = domain_end - domain_start;
uni_char* domain = OP_NEWA(uni_char, domain_end + 1);
RETURN_VALUE_IF_NULL(domain, NULL);
op_memcpy(domain, index->m_origin + domain_start, domain_end * sizeof(uni_char));
domain[domain_end] = 0;
index->m_domain = domain;
}
}
}
//after having the origin and the type, creating the file name will work
if (data_file_name != NULL)
{
RETURN_VALUE_IF_ERROR(PS_DataFile::Create(index, data_file_name), NULL);
OP_ASSERT(index->m_data_file_name != NULL);
}
if (name != NULL)
{
index->m_name = UniSetNewStr(name);
RETURN_VALUE_IF_NULL(index->m_name, NULL);
}
if (db_version != NULL)
{
index->m_db_version = UniSetNewStr(db_version);
RETURN_VALUE_IF_NULL(index->m_db_version, NULL);
}
index->m_ps_obj = ps_obj;
index->SetFlag(OBJ_INITIALIZED);
if (!is_persistent)
index->SetFlag(MEMORY_ONLY_DB);
ANCHOR_PTR_RELEASE(index);
return index;
}
PS_IndexEntry::PS_IndexEntry(PS_Manager* mgr) :
m_cached_file_size(0),
m_manager(mgr),
m_type(PS_ObjectTypes::KDBTypeStart),
m_origin(NULL),
m_name(NULL),
m_db_version(NULL),
m_context_id(DB_NULL_CONTEXT_ID),
m_domain(NULL),
m_data_file_name(NULL),
m_ps_obj(NULL),
m_res_policy(NULL),
m_quota_status(QS_DEFAULT)
{}
void PS_IndexEntry::Destroy()
{
if (m_ps_obj != NULL && !m_ps_obj->GetFlag(PS_Object::BEING_DELETED))
{
OP_DELETE(m_ps_obj);
//The deconstructor on PS_Object sets the m_index_entry.m_object property
//to NULL, so that's a sanity check making sure that happens.
//There are multiple cases where either the index entry or the
//ps_obj might be deleted, and these null assignments are
//there to make sure nothing keeps deleted pointers.
OP_ASSERT(m_ps_obj == NULL);
m_ps_obj = NULL;
}
if (m_data_file_name != NULL)
{
OP_ASSERT(m_data_file_name == GetPSManager()->GetNonPersistentFileName() ||
m_data_file_name->GetRefCount() == 1);
PS_DataFile_ReleaseOwner(m_data_file_name, this)
m_data_file_name->Release();
m_data_file_name = NULL;
}
OP_ASSERT(GetRefCount() == 0);
InvalidateCachedDataSize();
UnsetFlag(OBJ_INITIALIZED | OBJ_INITIALIZED_ERROR);
m_type = PS_ObjectTypes::KDBTypeStart;
if (m_origin != m_domain)
OP_DELETEA(m_domain);
m_domain = NULL;
OP_DELETEA(m_origin);
m_origin = NULL;
OP_DELETEA(m_name);
m_name = NULL;
OP_DELETEA(m_db_version);
m_db_version = NULL;
}
BOOL PS_IndexEntry::CompareVersion(const uni_char* other) const
{
return OpDbUtils::StringsEqual(
GetVersion() != NULL && *GetVersion() ? GetVersion() : NULL,
other != NULL && *other ? other : NULL);
}
OP_STATUS PS_IndexEntry::MakeAbsFilePath()
{
if (m_data_file_name == NULL)
{
RETURN_IF_ERROR(PS_DataFile::Create(this, NULL));
}
OP_ASSERT(m_data_file_name != NULL);
return m_data_file_name->MakeAbsFilePath();
}
BOOL PS_IndexEntry::Delete()
{
DB_DBG(("%p: PS_IndexEntry::Delete(" DB_DBG_ENTRY_STR "): %d, %p\n", this, DB_DBG_ENTRY_O(this), GetRefCount(), m_data_file_name))
SetFlag(MARKED_FOR_DELETION);
DeleteDataFile();
if (!IsIndexBeingDeleted() &&
!GetFlag(BEING_DELETED))
{
if (GetObject() != NULL)
{
OP_ASSERT(GetRefCount() != 0 || GetObject()->HasPendingActions());
return GetObject()->PreClearData();
}
else
{
OP_ASSERT(GetRefCount() == 0);
SetFlag(PURGE_ENTRY);
#ifdef SELFTEST
//this flag is unset when flushing stuff to disk is which is something done async
//for tests we want it to happen right away
if (m_manager->m_self_test_instance) UnsetFlag(MARKED_FOR_DELETION);
#endif //SELFTEST
return GetPSManager()->DeleteEntryNow(m_type, m_origin, m_name, !IsMemoryOnly(), m_context_id);
}
}
return FALSE;
}
void PS_IndexEntry::HandleObjectShutdown(BOOL should_delete)
{
DB_DBG(("%p: PS_IndexEntry::HandleObjectShutdown(" DB_DBG_ENTRY_STR "): %d, del: %s\n", this, DB_DBG_ENTRY_O(this), GetRefCount(), DB_DBG_BOOL(should_delete)))
OP_ASSERT(GetRefCount()==0);
m_ps_obj = NULL;
if ( should_delete || GetFlag(MARKED_FOR_DELETION) || IsMemoryOnly() || (GetFileRelPath() == NULL))
{
Delete();
}
}
OP_STATUS
PS_IndexEntry::GetDataFileSize(OpFileLength* file_size)
{
DB_ASSERT_RET(IsInitialized(), PS_Status::ERR_INVALID_STATE);
// Many steps involved in getting the data file size, read on
OP_ASSERT(file_size != NULL);
if (!GetFlag(HAS_CACHED_DATA_SIZE))
{
OpFileLength new_size = 0;
BOOL has_size = FALSE;
//1. evaluate the amount of data in memory
PS_Object *obj = GetObject();
if (obj != NULL && obj->IsInitialized())
{
OP_STATUS status = obj->EvalDataSizeSync(&new_size);
if (OpStatus::ERR_YIELD != status)
{
RETURN_IF_ERROR(status);
has_size = TRUE;
}
}
//2 .if we don't have the ps_obj object in memory, query file size directly
if (!has_size)
{
BOOL file_exists = FALSE;
RETURN_IF_ERROR(FileExists(&file_exists));
if (file_exists)
{
OP_ASSERT(GetOpFile() != NULL);
RETURN_IF_ERROR(GetOpFile()->GetFileLength(new_size));
has_size = TRUE;
}
}
if (!has_size)
new_size = 0;
m_cached_file_size = new_size;
SetFlag(HAS_CACHED_DATA_SIZE);
}
*file_size = m_cached_file_size;
return OpStatus::OK;
}
BOOL
PS_IndexEntry::DeleteDataFile()
{
if (m_data_file_name == NULL || IsMemoryOnly())
return FALSE;
if (GetQuotaHandlingStatus() != QS_WAITING_FOR_USER)
SetQuotaHandlingStatus(QS_DEFAULT);
//this will tag that the file needs to be deleted
PS_DataFile_ReleaseOwner(m_data_file_name, this)
m_data_file_name->SetWillBeDeleted();
m_data_file_name->Release();
m_data_file_name = NULL;
//after deleting the data file, the version no longer applies
OP_DELETEA(m_db_version);
m_db_version = NULL;
return TRUE;
}
void PS_IndexEntry::SetDataFileSize(const OpFileLength& file_size)
{
if (!GetFlag(HAS_CACHED_DATA_SIZE) || m_cached_file_size != file_size)
{
GetPSManager()->InvalidateCachedDataSize(GetType(), GetUrlContextId(), GetOrigin());
m_cached_file_size = file_size;
SetFlag(HAS_CACHED_DATA_SIZE);
}
}
PS_Policy* PS_IndexEntry::GetPolicy() const
{
return m_res_policy != NULL ? m_res_policy : g_database_policies->GetPolicy(m_type);
}
BOOL PS_IndexEntry::IsEqual(const PS_IndexEntry& rhs) const
{
return &rhs == this || IsEqual(rhs.m_type, rhs.m_origin, rhs.m_name, !rhs.IsMemoryOnly(), m_context_id);
}
BOOL PS_IndexEntry::IsEqual(PS_ObjectType type, const uni_char* origin,
const uni_char* name, BOOL is_persistent, URL_CONTEXT_ID context_id) const
{
DB_ASSERT_RET(IsInitialized(), FALSE);
is_persistent = !!is_persistent;
return IsMemoryOnly() != is_persistent &&
m_type == type &&
m_context_id == context_id &&
OpDbUtils::StringsEqual(m_origin, origin) &&
OpDbUtils::StringsEqual(m_name, name);
}
#undef RETURN_SIGN_IF_NON_0
#define RETURN_SIGN_IF_NON_0(x) do {int y=static_cast<int>(x);if(y!=0)return y<0?order:-order;} while(0)
int PS_IndexEntry::Compare(const PS_IndexEntry *lhs, const PS_IndexEntry *rhs, int order)
{
OP_ASSERT(lhs && rhs);
OP_ASSERT(order == -1 || order == 1);
RETURN_SIGN_IF_NON_0(rhs->m_context_id - lhs->m_context_id);
RETURN_SIGN_IF_NON_0(rhs->m_type - lhs->m_type);
if (rhs->m_origin != NULL && lhs->m_origin != NULL)
RETURN_SIGN_IF_NON_0(uni_stricmp(rhs->m_origin, lhs->m_origin));
else
RETURN_SIGN_IF_NON_0(PTR_TO_INT(rhs->m_origin) - PTR_TO_INT(lhs->m_origin));
if (rhs->m_name != NULL && lhs->m_name != NULL)
RETURN_SIGN_IF_NON_0(uni_stricmp(rhs->m_name, lhs->m_name));
else
RETURN_SIGN_IF_NON_0(PTR_TO_INT(rhs->m_name) - PTR_TO_INT(lhs->m_name));
return 0;
}
#undef RETURN_SIGN_IF_NON_0
/*static*/PS_Object*
PS_Object::Create(PS_IndexEntry* key)
{
switch(key->GetType())
{
#ifdef WEBSTORAGE_ENABLE_SIMPLE_BACKEND
case PS_ObjectTypes::KSessionStorage:
case PS_ObjectTypes::KLocalStorage:
return WebStorageBackend_SimpleImpl::Create(key);
#endif // WEBSTORAGE_ENABLE_SIMPLE_BACKEND
#ifdef DATABASE_STORAGE_SUPPORT
case PS_ObjectTypes::KWebDatabases:
return WSD_Database::Create(key);
#endif
#ifdef WEBSTORAGE_ENABLE_SIMPLE_BACKEND
#ifdef WEBSTORAGE_WIDGET_PREFS_SUPPORT
case PS_ObjectTypes::KWidgetPreferences:
return WebStorageBackend_SimpleImpl::Create(key);
#endif //WEBSTORAGE_WIDGET_PREFS_SUPPORT
#ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
case PS_ObjectTypes::KUserJsStorage:
return WebStorageBackend_SimpleImpl::Create(key);
#endif //WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
#endif //WEBSTORAGE_ENABLE_SIMPLE_BACKEND
}
OP_ASSERT(!"Bad type !");
return NULL;
}
/*static*/OP_STATUS
PS_Object::DeleteInstance(PS_ObjectType type, const uni_char* origin,
const uni_char* name, BOOL is_persistent, URL_CONTEXT_ID context_id)
{
return g_database_manager->DeleteObject(type, origin, name, is_persistent, context_id);
}
/*static*/OP_STATUS
PS_Object::DeleteInstances(PS_ObjectType type, URL_CONTEXT_ID context_id, const uni_char *origin, BOOL only_persistent)
{
return g_database_manager->DeleteObjects(type, context_id, origin, only_persistent);
}
/*static*/OP_STATUS
PS_Object::DeleteInstances(PS_ObjectType type, URL_CONTEXT_ID context_id, BOOL only_persistent)
{
return g_database_manager->DeleteObjects(type, context_id, only_persistent);
}
/*static*/OP_STATUS
PS_Object::GetInstance(PS_ObjectType type, const uni_char* origin,
const uni_char* name, BOOL is_persistent, URL_CONTEXT_ID context_id, PS_Object** object)
{
return g_database_manager->GetObject(type, origin, name, is_persistent, context_id, object);
}
PS_Object::PS_Object(PS_IndexEntry* entry) : m_index_entry(entry)
{
OP_ASSERT(entry != NULL);
entry->m_ps_obj = this;
}
#ifdef OPSTORAGE_SUPPORT
PS_ObjectTypes::PS_ObjectType WebStorageTypeToPSObjectType(WebStorageType ws_t)
{
#ifdef WEBSTORAGE_ENABLE_SIMPLE_BACKEND
switch(ws_t)
{
case WEB_STORAGE_SESSION:
return PS_ObjectTypes::KSessionStorage;
case WEB_STORAGE_LOCAL:
return PS_ObjectTypes::KLocalStorage;
#ifdef WEBSTORAGE_WIDGET_PREFS_SUPPORT
case WEB_STORAGE_WGT_PREFS:
return PS_ObjectTypes::KWidgetPreferences;
#endif //WEBSTORAGE_WIDGET_PREFS_SUPPORT
#ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
case WEB_STORAGE_USERJS:
return PS_ObjectTypes::KUserJsStorage;
#endif //WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
}
#endif //WEBSTORAGE_ENABLE_SIMPLE_BACKEND
OP_ASSERT(!"Missing storage type");
return PS_ObjectTypes::KDBTypeStart;
}
WebStorageType PSObjectTypeToWebStorageType(PS_ObjectTypes::PS_ObjectType db_t)
{
#ifdef WEBSTORAGE_ENABLE_SIMPLE_BACKEND
switch(db_t)
{
case PS_ObjectTypes::KSessionStorage:
return WEB_STORAGE_SESSION;
case PS_ObjectTypes::KLocalStorage:
return WEB_STORAGE_LOCAL;
#ifdef WEBSTORAGE_WIDGET_PREFS_SUPPORT
case PS_ObjectTypes::KWidgetPreferences:
return WEB_STORAGE_WGT_PREFS;
#endif //WEBSTORAGE_WIDGET_PREFS_SUPPORT
#ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
case PS_ObjectTypes::KUserJsStorage:
return WEB_STORAGE_USERJS;
#endif //WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
}
#endif //WEBSTORAGE_ENABLE_SIMPLE_BACKEND
OP_ASSERT(!"Missing storage type");
return WEB_STORAGE_START;
}
#endif // OPSTORAGE_SUPPORT
#endif //DATABASE_MODULE_MANAGER_SUPPORT
|
#ifndef CONNECTOR
#define CONNECTOR
#include "message.hpp"
#include <iostream>
#include <sstream>
#include <vector>
#include <cstring>
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "Mswsock.lib")
#pragma comment(lib, "AdvApi32.lib")
#include <basetsd.h>
typedef SSIZE_T ssize_t;
#else
#include <netdb.h>
#include <unistd.h>
#endif
namespace cpprofiler {
template <typename T>
class Option {
T value_;
bool present{false};
public:
bool valid() const { return present; }
void set(const T& t) { present = true; value_ = t; }
void unset() { present = false; }
const T& value() const { assert(present); return value_; }
T& value() { assert(present); return value_; }
};
class Connector;
class Node;
static void sendNode(Connector& c, Node& node);
class Node {
Connector& _c;
NodeUID node_;
NodeUID parent_;
int alt_;
int kids_;
NodeStatus status_;
Option<std::string> label_;
Option<std::string> nogood_;
Option<std::string> info_;
public:
Node(NodeUID node, NodeUID parent,
int alt, int kids, NodeStatus status, Connector& c)
: _c(c), node_{node}, parent_{parent},
alt_(alt), kids_(kids), status_(status) {}
Node& set_node_thread_id(int tid) {
node_.tid = tid;
return *this;
}
const Option<std::string>& label() const { return label_; }
Node& set_label(const std::string& label) {
label_.set(label);
return *this;
}
const Option<std::string>& nogood() const { return nogood_; }
Node& set_nogood(const std::string& nogood) {
nogood_.set(nogood);
return *this;
}
const Option<std::string>& info() const { return info_; }
Node& set_info(const std::string& info) {
info_.set(info);
return *this;
}
int alt() const { return alt_; }
int kids() const { return kids_; }
NodeStatus status() const { return status_; }
NodeUID nodeUID() const { return node_; }
NodeUID parentUID() const { return parent_; }
int node_id() const { return node_.nid; }
int parent_id() const { return parent_.nid; }
int node_thread_id() const { return node_.tid; }
int node_restart_id() const { return node_.rid; }
int parent_thread_id() const { return parent_.tid; }
int parent_restart_id() const { return parent_.rid; }
void send() { sendNode(_c, *this); }
};
// From http://beej.us/guide/bgnet/output/html/multipage/advanced.html#sendall
static int sendall(int s, const char* buf, int* len) {
int total = 0; // how many bytes we've sent
int bytesleft = *len; // how many we have left to send
ssize_t n;
while (total < *len) {
n = send(s, buf + total, static_cast<size_t>(bytesleft), 0);
if (n == -1) {
break;
}
total += n;
bytesleft -= n;
}
*len = total; // return number actually sent here
return n == -1 ? -1 : 0; // return -1 on failure, 0 on success
}
class Connector {
private:
MessageMarshalling marshalling;
const unsigned int port;
int sockfd;
bool _connected;
void sendOverSocket() {
if (!_connected) return;
std::vector<char> buf = marshalling.serialize();
sendRawMsg(buf);
}
public:
void sendRawMsg(const std::vector<char>& buf) {
uint32_t bufSize = static_cast<uint32_t>(buf.size());
int bufSizeLen = sizeof(uint32_t);
sendall(sockfd, reinterpret_cast<char*>(&bufSize), &bufSizeLen);
int bufSizeInt = static_cast<int>(bufSize);
sendall(sockfd, reinterpret_cast<const char*>(buf.data()), &bufSizeInt);
}
Connector(unsigned int port) : port(port), _connected(false) {}
bool connected() { return _connected; }
/// connect to a socket via port specified in the construction (6565 by
/// default)
void connect() {
struct addrinfo hints, *servinfo, *p;
int rv;
#ifdef WIN32
// Initialise Winsock.
WSADATA wsaData;
int startupResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (startupResult != 0) {
printf("WSAStartup failed with error: %d\n", startupResult);
}
#endif
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo("localhost", std::to_string(port).c_str(), &hints,
&servinfo)) != 0) {
std::cerr << "getaddrinfo: " << gai_strerror(rv) << "\n";
goto giveup;
}
// loop through all the results and connect to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
// errno is set here, but we don't examine it.
continue;
}
if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
#ifdef WIN32
closesocket(sockfd);
#else
close(sockfd);
#endif
// errno is set here, but we don't examine it.
continue;
}
break;
}
// Connection failed; give up.
if (p == NULL) {
goto giveup;
}
freeaddrinfo(servinfo); // all done with this structure
_connected = true;
return;
giveup:
_connected = false;
return;
}
// sends START_SENDING message to the Profiler with a model name
void start(const std::string& file_path = "",
int execution_id = -1, bool has_restarts = false) {
/// extract fzn file name
std::string base_name(file_path);
{
size_t pos = base_name.find_last_of('/');
if (pos != static_cast<size_t>(-1)) {
base_name = base_name.substr(pos + 1, base_name.length() - pos - 1);
}
}
std::string info{""};
{
std::stringstream ss;
ss << "{";
ss << "\"has_restarts\": " << (has_restarts ? "true" : "false") << "\n";
ss << ",\"name\": " << "\"" << base_name << "\"" << "\n";
if (execution_id != -1) {
ss << ",\"execution_id\": " << execution_id;
}
ss << "}";
info = ss.str();
}
marshalling.makeStart(info);
sendOverSocket();
}
void restart(int restart_id = -1) {
std::string info{""};
{
std::stringstream ss;
ss << "{";
ss << "\"restart_id\": " << restart_id << "\n";
ss << "}";
info = ss.str();
}
marshalling.makeRestart(info);
sendOverSocket();
}
void done() {
marshalling.makeDone();
sendOverSocket();
}
/// disconnect from a socket
void disconnect() {
#ifdef WIN32
closesocket(sockfd);
#else
close(sockfd);
#endif
}
void sendNode(const Node& node) {
if (!_connected) return;
auto& msg = marshalling.makeNode(node.nodeUID(), node.parentUID(),
node.alt(), node.kids(), node.status());
if (node.label().valid()) msg.set_label(node.label().value());
if (node.nogood().valid()) msg.set_nogood(node.nogood().value());
if (node.info().valid()) msg.set_info(node.info().value());
sendOverSocket();
}
Node createNode(NodeUID node, NodeUID parent,
int alt, int kids, NodeStatus status) {
return Node(node, parent, alt, kids, status, *this);
}
};
void sendNode(Connector& c, Node& node) { c.sendNode(node); }
}
#endif
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int n,k,m1,m2,sum=0;
while(scanf("%d %d",&n,&k)==2)
{
sum=n;
m1=n/k;
m2=n%k;
n=m1+m2;
if(n>=k)
{
sum+=m1;
while(k<=n)
{
m1=n/k;
m2=n%k;
n=m1+m2;
sum+=m1;
}
printf("%d\n",sum);
sum=0;
}
else
{
sum+=m1;
printf("%d\n",sum);
sum=0;
}
}
return 0;
}
|
// Created on: 2002-04-15
// Created by: Alexander Kartomin (akm)
// Copyright (c) 2002-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.
// Automatically created from NCollection_Array2.hxx by GAWK
// Purpose: The class Array2 represents bi-dimensional arrays
// of fixed size known at run time.
// The ranges of indices are user defined.
// Warning: Programs clients of such class must be independent
// of the range of the first element. Then, a C++ for
// loop must be written like this
// for (i = A.LowerRow(); i <= A.UpperRow(); i++)
// for (j = A.LowerCol(); j <= A.UpperCol(); j++)
#ifndef NCollection_DefineArray2_HeaderFile
#define NCollection_DefineArray2_HeaderFile
#include <NCollection_Array2.hxx>
// *********************************************** Template for Array2 class
#define DEFINE_ARRAY2(_ClassName_, _BaseCollection_, TheItemType) \
typedef NCollection_Array2<TheItemType > _ClassName_;
#endif
|
#pragma once
#include "Render/DrawBasic/BufferLayout.h"
namespace Rocket
{
Interface IndexBuffer
{
public:
virtual ~IndexBuffer() = default;
virtual void Bind() const = 0;
virtual void Unbind() const = 0;
virtual uint32_t GetCount() const = 0;
};
}
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
vector<int> v;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
while(n--){
int tp;
cin >> tp;
v.push_back(tp);
}
sort(v.begin(), v.end());
int ans = 0;
int sum = 0;
for(int num : v){
sum += num;
ans = ans + sum;
}
cout << ans << '\n';
return 0;
}
|
//============================================================================
// Name : functions.cpp
// Author : Ben Newey
// Version :
// Copyright : Your copyright notice
// Description : All basic functions for port reading / mysql / json sending to UI
//============================================================================
// C library headers
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <jsoncpp/json/json.h>
// Linux headers
#include <fcntl.h> // Contains file controls like O_RDWR
#include <errno.h> // Error integer and strerror() function
#include <termios.h> // Contains POSIX terminal control definitions
#include <unistd.h> // write(), read(), close()
#include <sys/file.h>
#include <sys/socket.h>
#include <vector>
#include <iostream>
#include <iomanip>
#include <sys/time.h>
#include <sys/types.h>
// Socket header
#include <netinet/in.h>
#include <mysql/mysql.h>
#include "./mode.cpp"
#define PORT 8081
using namespace std;
const short BUFF_SIZE = 102;
void print_buf(char (&read_buf)[BUFF_SIZE], int numIterations, int numReads){
cout<< numReads << ": "<<endl<<"Print iterations: "<< numIterations<<endl;
for (int i = 0; i < BUFF_SIZE; ++i)
cout << hex << setfill('0') << setw(2) << (int)(*(unsigned char*)(&read_buf[i])) << dec << " ";
cout <<endl<<endl;
}
void print_write_buff(char (&write_buf)[102], int numIterations, int numReads){
cout<< numReads << ": "<<endl<<"Write iterations: "<< numIterations<<endl;
for (int i = 0; i < 102; ++i)
cout << hex << setfill('0') << setw(2) << (int)(*(unsigned char*)(&write_buf[i])) << dec << " ";
cout <<endl<<endl;
}
int read_bytes(char (&read_buf)[BUFF_SIZE],int & serial_port , int & numIterations) {
/* reading above 255 is tricky, we need to read BUFFSIZE bytes exactly, so this ensures it */
int totalNeeded = BUFF_SIZE;
int remaining = sizeof(read_buf);
numIterations=0;
int totalRead = 0;
//reset first byte to 0 because thats what we check against for validation
read_buf[0] = 0x00;
while (remaining > 0){
try{
int in;
ioctl(serial_port, FIONREAD, &in);
//cout<<"IN READ"<<in<<endl;
ssize_t readChars = read(serial_port, &read_buf[totalNeeded - remaining], remaining);
//cout<<"Read Chars: "<<dec<<readChars<<endl;
if (!(readChars > 0)){
return totalRead;
}
else{
cout<<"readchars: "<<readChars<<endl;
remaining -= readChars;
numIterations++;
totalRead+=readChars;
print_buf(read_buf, numIterations, remaining);
}
} catch(ssize_t readChars){
cout<<"Read exception caught"<<endl;
}
}
if(read_buf[0] != 0x02){
cout<<"ERROR: BAD INPUT FROM COM PORT"<<endl;
//print_buf(read_buf, 1 ,1);
//return -1;
}
return(totalRead);
}
void getPressuresLH(char (&read_buf)[BUFF_SIZE], int & low_pressure, int & high_pressure, bool & compressor){
// Convert both the integers to string
// 3+4 = pressure low | 5+6 = pressure high
int pressure_l = ((int)(*(unsigned char*)(&read_buf[1]))<<8) | ((int)(*(unsigned char*)(&read_buf[2])));
int pressure_h = ((int)(*(unsigned char*)(&read_buf[3]))<<8) | ((int)(*(unsigned char*)(&read_buf[4])));
int compress_tmp = read_buf[21];
low_pressure = pressure_l;
high_pressure = pressure_h;
compressor = compress_tmp;
}
void editWriteBuf(char (&temp)[102], ModeHandler mh){
temp[0] = 0x02;
temp[1] = 0x00; //fake pressure spot
temp[2] = 0x11; //fake pressure spot
temp[3] = 0x00; //fake pressure spot
temp[4] = 0x11; //fake pressure spot
temp[5] = (mh.getRelayStart() ? 0x01 : 0x00);
temp[6] = (mh.getRelayStop() ? 0x01 : 0x00);
temp[7] = (mh.getRelayBleed() ? 0x01 : 0x00);
temp[8] = (mh.getRelayMotor() ? 0x01 : 0x00);
temp[9] = (mh.getRelayPump() ? 0x01 : 0x00);
temp[10] = (mh.getRelayChiller() ? 0x01 : 0x00);
for(int i=0; i<90;i++) { //space for later boards
temp[i+11] = 0x00;
}
temp[101] = 0xaa;
}
void write_bytes(int & serial_port, char (&temp)[102]){
write(serial_port, temp, 102);//sizeof(temp));
}
int usb_port(int & serial_port) {
//TODO: try /dev/ttyUSB* instead of 0, bc linux might overwrite USB0
serial_port = open("/dev/ttyUSB0", O_RDWR );
usleep(10000);
//Check for errors
if (serial_port < 0) {
printf("Error %i from open: %s\n", errno, strerror(errno));
return(serial_port);
}
else{
// Create new termios struc, we call it 'tty' for convention
struct termios tty;
memset(&tty, 0, sizeof tty);
// Read in existing settings, and handle any error
if(tcgetattr(serial_port, &tty) != 0) {
// printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
}
tty.c_cflag &= ~PARENB; // Clear parity bit, disabling parity (most common)
tty.c_cflag &= ~CSTOPB; // Clear stop field, only one stop bit used in communication (most common)
tty.c_cflag |= CS8; // 8 bits per byte (most common)
//"Enabling this when it should be disabled can result in your serial port receiving no data"
tty.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hardware flow control (most common)
tty.c_cflag |= CREAD | CLOCAL; // Turn on READ & ignore ctrl lines (CLOCAL = 1)
tty.c_lflag &= ~ICANON; //Canonical mode is disabled
//If this bit is set, sent characters will be echoed back.
tty.c_lflag &= ~ECHO; // Disable echo
tty.c_lflag &= ~ECHOE; // Disable erasure
tty.c_lflag &= ~ECHONL; // Disable new-line echo
tty.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP (We don’t want this with a serial port)
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off software flow control
tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received bytes, we just want raw data
tty.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars)
tty.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed
// tty.c_oflag &= ~OXTABS; // Prevent conversion of tabs to spaces (NOT PRESENT IN LINUX)
// tty.c_oflag &= ~ONOEOT; // Prevent removal of C-d chars (0x004) in output (NOT PRESENT IN LINUX)
//tty.c_cc[VTIME] = 2; // Wait for up to 1s (10 deciseconds), returning as soon as any data is received.
//tty.c_cc[VMIN] = 0; //wait for BUFF_SIZE bytes to fill then return
tty.c_cc[VTIME] = 2; // Wait for up to 1s (10 deciseconds), returning as soon as any data is received.
tty.c_cc[VMIN] = 0; //wait for BUFF_SIZE bytes to fill then return
// Set in/out baud rate to be 9600
// If you have no idea what the baud rate is and you are trying to communicate with a 3rd party system,
// try B9600, then B57600 and then B115200 as they are the most common rates.
cfsetispeed(&tty, B57600);
cfsetospeed(&tty, B57600);
if (tcflush(serial_port, TCIOFLUSH) == 0)
printf("The input and output queues have been flushed.n");
else
perror("tcflush error");
// Save tty settings, also checking for error
if (tcsetattr(serial_port, TCSANOW, &tty) != 0) {
// printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
}
//prevent other processes from reading/writing to the serial port at the same time you are.
if(flock(serial_port, LOCK_EX | LOCK_NB) == -1) {
throw std::runtime_error("Serial port with file descriptor " +
std::to_string(serial_port) + " is already locked by another process.");
}
return(serial_port);
}
}
void mysqlConnect(MYSQL & mysql){
//Connect to MySQL server
mysql_init(&mysql);
mysql_options(&mysql,MYSQL_READ_DEFAULT_GROUP,"nitrogen");
printf("MYSQL INFO: %s\n", mysql_get_client_info());
if (!mysql_real_connect(&mysql,"127.0.0.1","root","!Baseball15","db_nitro",0,NULL,0))
{
fprintf(stderr, "Failed to connect to database: Error: %s\n",
mysql_error(&mysql));
return;
}
cout<<"Successfully Connected to MYSQL"<<endl;
return;
}
int mysqlQuery(MYSQL & mysql, vector<string> & return_array, const char * field_name){
//TODO: Are mutliple return point good or bad practice???
//TODO: Select machine_table_name instead of *
unsigned int num_fields;
MYSQL_ROW row;
if(mysql_query(&mysql, "SELECT * from machines")){
cout<<"MySQL Query Error"<<endl;
return 0;
}
MYSQL_RES *result = mysql_store_result(&mysql);
if(!result){
fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
return 0;
}
//Find index of field_name and field_table_name
num_fields = mysql_num_fields(result);
MYSQL_FIELD *fields;
fields = mysql_fetch_fields(result);
unsigned int field_name_index;
bool field_name_index_found = false;
for(unsigned int i = 0; i < num_fields; i++){
if(!(strcmp(fields[i].name , field_name))){
field_name_index = i;
field_name_index_found = true;
}
}
if(!field_name_index_found){
cout<<" Warning on mysql query: Bad field name in mySqlQuery()"<<endl;
}
//Search through rows
while ((row = mysql_fetch_row(result))) {
for(unsigned int p = 0; p < num_fields; p++) {
//if field matches our field_name or field_table_name from above, record that cell
if(p == field_name_index){
string t = row[p];
return_array.push_back(t);
}
}
}
// //Print Vector
for (std::vector<string>::const_iterator i = return_array.begin(); i != return_array.end(); ++i)
std::cout << *i << ' ';
cout<<endl;
mysql_free_result(result);
return 1;
}
int mysqlQueryFixed(MYSQL & mysql, vector< vector<string> > & return_array){
unsigned int num_fields;
MYSQL_ROW row;
if(mysql_query(&mysql, "SELECT * FROM mode_variables ORDER BY id ASC")){
cout<<"MySQL Query Error"<<endl;
return 0;
}
MYSQL_RES *result = mysql_store_result(&mysql);
if(!result){
fprintf(stderr, "Error: %s\n", mysql_error(&mysql));
return 0;
}
//Clear return_array
return_array.clear();
//Find index of field_name and field_table_name
num_fields = mysql_num_fields(result);
//Search through rows
int k = 0;
while ((row = mysql_fetch_row(result))) {
vector<string> tmp;
for(unsigned int p = 0; p < num_fields; p++) {
string t = row[p];
tmp.push_back(t);
}
// //Print Vector
for (std::vector<string>::const_iterator i = tmp.begin(); i != tmp.end(); ++i)
std::cout << *i << ' ';
return_array.push_back(tmp);
k++;
}
mysql_free_result(result);
return 1;
}
void mysqlCloseConnect(MYSQL &mysql){
mysql_close(&mysql);
}
int readNodeSocket( int & new_socket, char (&ui_buf)[4] ){
int valread;
ui_buf[0] = '\0';
//valread = read( new_socket , buffer, 1024);
valread = recv( new_socket, ui_buf,4, 0);
return(valread);
}
void sendNodeSocket(int & new_socket, char const * data, const unsigned short DATA_SIZE){
try{
send(new_socket , data , DATA_SIZE , 0 );
//printf("Data message sent from C++\n");
}
catch (int e){
printf("*** could not send data ***");
}
}
int nodeSocket(int & server_fd){
int new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
cout<<"*** Failed to create socket ***"<<endl;
exit(EXIT_FAILURE);
}
cout<< "Created Socket "<<endl;
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
cout<<"*** Failed to run setsockopt() ***"<<endl;
exit(EXIT_FAILURE);
}
// set a timeout for client to connect / read from
struct timeval tv;
tv.tv_sec = 10;
tv.tv_usec = 0;
if (setsockopt(server_fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv)){
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
int error_num = bind(server_fd, (struct sockaddr *)&address, sizeof(address));
if(error_num < 0 ){
cout<<"*** Bind Failed ***"<<endl;
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
cout<<"*** listen ***"<<endl;
exit(EXIT_FAILURE);
}
// socket blocks program on accept() until either a client accepts or timeout occurs
int error_num2 = new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);
if(error_num2 < 0){
cout<<"*** No Client Accepted Connection *** - "<<errno<<endl;
return -1;
}
return new_socket;
}
string createJsonDataString(char (&read_buf)[BUFF_SIZE], int pressure_low, int pressure_high, bool compressor, ModeHandler mh, long numJsonSends){
int temp=0;
float timer_temp=0.00;
bool mode_start_stop = 0;
int current_mode=0;
vector<Json::Value> arrayVehicles;
Json::Value root;
Json::Value myJson = root["nitrogenData"];
myJson["id"] = Json::Value::Int(numJsonSends);
myJson["pressure_low"] = Json::Value::Int(pressure_low);
myJson["pressure_high"] = Json::Value::Int(pressure_high);
//Compressor on or off
myJson["compressor"] = Json::Value::Int(compressor);
//pressure_low and pressure_high are 2 bits
string data_string_template[6] = {"relay_start", "relay_stop", "relay_bleed","relay_motor", "relay_pump", "relay_chiller"};
for(int p= 0;p < 6; p++){
stringstream ss;
ss.clear();
ss << hex << setfill('0') << setw(2) << (int)(*(unsigned char*)(&read_buf[p+5])); //offset by 5 to get to the relays readbuf[5-11]
ss >> temp;
myJson[data_string_template[p]] = Json::Value::Int(temp);
}
//Timers
timer_temp = mh.getTimerMode2();
myJson["timer_mode2"] = Json::Value::Int(timer_temp);
timer_temp = mh.getTimerMode4();
myJson["timer_mode4"] = Json::Value::Int(timer_temp);
timer_temp = mh.getTimerStartRelay();
myJson["timer_start_relay"] = Json::Value::Int(timer_temp);
timer_temp = mh.getTimerStopRelay();
myJson["timer_stop_relay"] = Json::Value::Int(timer_temp);
timer_temp = mh.getTimerBleedRelay();
myJson["timer_bleed_relay"] = Json::Value::Int(timer_temp);
timer_temp = mh.getTimerMotorRelay();
myJson["timer_motor_relay"] = Json::Value::Int(timer_temp);
timer_temp = mh.getTimerShutDownCounter();
myJson["timer_shut_down_counter"] = Json::Value::Int(timer_temp);
//Current Mode
current_mode = mh.getCurrentMode();
myJson["current_mode"] = Json::Value::Int(current_mode);
//Start Stop Indicator
mode_start_stop = mh.getStartStopValue();
myJson["start_stop"] = Json::Value::Int(mode_start_stop);
arrayVehicles.push_back(myJson);
Json::FastWriter fastWriter;
string output = "{ \"nitrogenData\": ";
for(int i=0; i<1; i++){
if(i != 0)
output += ",";
output += fastWriter.write(arrayVehicles[i]);
}
output += " }";
cout<<"OUTPUT"<<output<<endl;
return(output);
}
string createJsonString(string message){
Json::Value root;
Json::Value myJson = root["nitrogenData"];
myJson["error"] = Json::Value::Int(1);
Json::FastWriter fastWriter;
string output = "{ \"nitrogenData\": ";
output += fastWriter.write(myJson);
output += " }";
return(output);
}
|
/****************************************************************************
** Meta object code from reading C++ file 'relationediteur.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../PluriNote/relationediteur.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'relationediteur.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.8.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_RelationEditeur_t {
QByteArrayData data[9];
char stringdata0[113];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_RelationEditeur_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_RelationEditeur_t qt_meta_stringdata_RelationEditeur = {
{
QT_MOC_LITERAL(0, 0, 15), // "RelationEditeur"
QT_MOC_LITERAL(1, 16, 11), // "setOriented"
QT_MOC_LITERAL(2, 28, 0), // ""
QT_MOC_LITERAL(3, 29, 13), // "modifierLabel"
QT_MOC_LITERAL(4, 43, 9), // "addCouple"
QT_MOC_LITERAL(5, 53, 15), // "supprimerCouple"
QT_MOC_LITERAL(6, 69, 8), // "ssetList"
QT_MOC_LITERAL(7, 78, 18), // "afficherRafraichir"
QT_MOC_LITERAL(8, 97, 15) // "afficherBoutons"
},
"RelationEditeur\0setOriented\0\0modifierLabel\0"
"addCouple\0supprimerCouple\0ssetList\0"
"afficherRafraichir\0afficherBoutons"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_RelationEditeur[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
7, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 49, 2, 0x0a /* Public */,
3, 0, 50, 2, 0x0a /* Public */,
4, 0, 51, 2, 0x0a /* Public */,
5, 0, 52, 2, 0x0a /* Public */,
6, 0, 53, 2, 0x0a /* Public */,
7, 0, 54, 2, 0x08 /* Private */,
8, 0, 55, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void RelationEditeur::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
RelationEditeur *_t = static_cast<RelationEditeur *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->setOriented(); break;
case 1: _t->modifierLabel(); break;
case 2: _t->addCouple(); break;
case 3: _t->supprimerCouple(); break;
case 4: _t->ssetList(); break;
case 5: _t->afficherRafraichir(); break;
case 6: _t->afficherBoutons(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject RelationEditeur::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_RelationEditeur.data,
qt_meta_data_RelationEditeur, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *RelationEditeur::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *RelationEditeur::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_RelationEditeur.stringdata0))
return static_cast<void*>(const_cast< RelationEditeur*>(this));
return QWidget::qt_metacast(_clname);
}
int RelationEditeur::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 7)
qt_static_metacall(this, _c, _id, _a);
_id -= 7;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 7)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 7;
}
return _id;
}
struct qt_meta_stringdata_ReferenceEditeur_t {
QByteArrayData data[1];
char stringdata0[17];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_ReferenceEditeur_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_ReferenceEditeur_t qt_meta_stringdata_ReferenceEditeur = {
{
QT_MOC_LITERAL(0, 0, 16) // "ReferenceEditeur"
},
"ReferenceEditeur"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_ReferenceEditeur[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void ReferenceEditeur::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject ReferenceEditeur::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_ReferenceEditeur.data,
qt_meta_data_ReferenceEditeur, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *ReferenceEditeur::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *ReferenceEditeur::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_ReferenceEditeur.stringdata0))
return static_cast<void*>(const_cast< ReferenceEditeur*>(this));
return QWidget::qt_metacast(_clname);
}
int ReferenceEditeur::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#include "core/pch.h"
#if defined(_NATIVE_SSL_SUPPORT_)
#include "modules/libssl/sslbase.h"
#include "modules/libssl/protocol/sslstat.h"
#include "modules/url/url2.h"
#include "modules/url/url_sn.h"
#include "modules/url/url_man.h"
#include "modules/url/protocols/http1.h"
#include "modules/hardcore/mem/mem_man.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/libssl/method_disable.h"
SSL_SessionStateRecord::SSL_SessionStateRecord()
{
InternalInit();
}
void SSL_SessionStateRecord::InternalInit()
{
//servername = NULL;
//port = 0;
//tls_disabled = FALSE;
last_used = 0;
is_resumable = TRUE;
session_negotiated = FALSE;
connections = 0;
cipherdescription =NULL;
security_rating = SECURITY_STATE_UNKNOWN;
low_security_reason = SECURITY_REASON_NOT_NEEDED;
used_compression = SSL_Null_Compression;
used_correct_tls_no_cert = FALSE;
use_correct_tls_no_cert = TRUE;
UserConfirmed = NO_INTERACTION;
certificate_status = SSL_CERT_NO_WARN;
renegotiation_extension_supported = FALSE;
#ifdef SSL_CHECK_EXT_VALIDATION_POLICY
extended_validation = FALSE;
#endif
#ifndef TLS_NO_CERTSTATUS_EXTENSION
ocsp_extensions_sent=FALSE;
#endif
#ifdef _SECURE_INFO_SUPPORT
session_information = NULL;
#endif
}
#ifdef _SECURE_INFO_SUPPORT
void SSL_SessionStateRecord::DestroySessionInformation()
{
session_information_lock.UnsetURL();
OP_DELETE(session_information);
session_information = NULL;
}
#endif
SSL_SessionStateRecord::~SSL_SessionStateRecord()
{
#ifdef _SECURE_INFO_SUPPORT
DestroySessionInformation();
#endif
}
SSL_SessionStateRecordList::SSL_SessionStateRecordList()
{
}
SSL_SessionStateRecordList::~SSL_SessionStateRecordList()
{
if(InList())
Out();
}
#endif
|
//
// Created by user24 on 2019/11/16.
//
#ifndef LAB_DS_LAB3_BITREE_CC
#define LAB_DS_LAB3_BITREE_CC
#include <fstream>
#include "BiTree.hh"
#include "BiNode.hh"
namespace lab3 {
template<typename T>
auto BiTree<T>::length() -> size_t {
size_t length = 0;
preOrder([&length](Node &node) {
return length++, true;
});
return length;
}
template<typename T>
auto BiTree<T>::create(std::vector<lab3::StringKeyValuePair<T>> &kvPairs, size_t const current) -> size_t {
if (current < 0 || current == kvPairs.size() - 1 || kvPairs[current].key == "") { return -1; }
_root = std::make_unique<Node>(kvPairs[current]);
return root()->create(kvPairs, current + 1);
}
template<typename T>
auto BiTree<T>::save(std::string const &filename) -> void {
std::ofstream f;
f.open(filename);
size_t extendedLength = 0;
root()->extendedPreOrder([&extendedLength](Node &node) { return extendedLength++, true; },
[&extendedLength] { extendedLength++; });
f << extendedLength << std::endl;
root()->extendedPreOrder(
[&f](Node &node) {
if (node.key() != "") {
f << node.key() << std::endl;
f << node.val() << std::endl;
} else {
f << "" << std::endl;
}
return true;
},
[&f] { f << "" << std::endl; }
);
f.close();
}
template<typename T>
auto BiTree<T>::load(std::string const &filename) -> void {
using KVP = StringKeyValuePair<T>;
std::fstream f(filename, std::ios_base::in);
size_t len = 0;
f >> len;
f.get();
std::vector<KVP> kvPairs;
for (size_t i = 0; i < len; i++) {
std::string key;
T val = 0;
// f >> key;
std::getline(f, key);
if (!key.empty()) {
f >> val;
f.get();
// std::getline(f, val);
}
kvPairs.push_back(KVP{key, val});
}
f.close();
create(kvPairs);
}
}
#endif //LAB_DS_LAB3_BITREE_CC
|
#include "SceneRenderer.h"
#include <glm/gtx/transform.hpp>
#include "../OpenGL/RenderTarget.h"
#include "../OpenGL/VertexArray.h"
#include "../OpenGL/Shader.h"
#include "../OpenGL/MeshGenerator.h"
#include "../OpenGL/TextureCubeMap.h"
#include "../OpenGL/OpenGLState.h"
#include "../OpenGL/Camera.h"
#include "../OpenGL/Texture.h"
#include "../OpenGL/Texture2D.h"
#include "../ImGui/imgui.h"
#include "../Utils/RandomUtils.h"
#include <iostream>
SceneRenderer::SceneRenderer()
{
_terrainShader = std::make_shared<Shader>("shaders/terrain.vert", "shaders/terrain.frag", nullptr, false);
// Must bind shader before setting a uniform variable!
_terrainShader->Start();
_terrainShader->Set("tex0", 0);
_terrainShader->Set("tex1", 1);
_terrainShader->End();
_terrainScale = glm::vec3(32.0, 4.0, 32.0);
// create terrain
int hWidth, hHeight;
float* heightMapData = Texture::loadHeightMap("textures/heightMapLow.png", &hWidth, &hHeight);
if (heightMapData != nullptr)
{
_terrain = generateTerrain(heightMapData, glm::ivec2(hWidth, hHeight), _terrainScale);
Texture::freeImage(heightMapData);
}
else
{
_terrain = generateBox(glm::vec3(0.0), glm::vec3(1.0));
}
_terrainTex0 = std::make_shared<Texture2D>("textures/grass.jpg");
_terrainTex0->bind();
_terrainTex0->setWrapping(GL_REPEAT);
_terrainTex1 = std::make_shared<Texture2D>("textures/rock.png");
_terrainTex1->bind();
_terrainTex1->setWrapping(GL_REPEAT);
}
SceneRenderer::~SceneRenderer()
{
}
void SceneRenderer::Gui()
{
}
void SceneRenderer::Draw(std::shared_ptr<RenderTarget> target, std::shared_ptr<TextureCubeMap> skyboxTexture, std::shared_ptr<Camera> camera, glm::vec3 sunDir, float sunPower)
{
CullFace();
_terrainShader->Start();
auto model = glm::mat4(1.0);
model = glm::translate(model, glm::vec3(-16.0, 2.0, -16.0));
_terrainShader->Set("model", model);
_terrainShader->Set("normalMatrix", GetNormalMatrix(model));
_terrainShader->Set("projView", camera->ProjectionViewMatrix());
_terrainShader->Set("sunDir", sunDir);
_terrainShader->Set("sunPower", sunPower);
_terrainShader->Set("cameraPos", camera->Position);
_terrainTex0->use(0);
_terrainTex1->use(1);
_terrain->draw();
_terrainShader->End();
DisableCullFace();
}
|
#include <iostream>
#include <cstring>
#include "preprocess.h"
#include "lexical.h"
#include "preprocess.h"
#include "grammar.h"
#include "parser.h"
#include "rep/prog.h"
#include "interpreter.h"
using namespace std;
string workDir;
string getFolder (const string& str) {
size_t found;
found=str.find_last_of("/\\");
return str.substr(0,found+1);
}
string getWorkDir() {
return workDir;
}
int analyse_arg(int argc, char** argv, char* file) {
if(argc == 2) {
strcpy(file, argv[1]);
return 0;
}
return 9;
}
int main(int argc, char** argv) {
char* file = new char[100];
int result = analyse_arg(argc, argv, file);
workDir = getFolder(file);
init(); //init de la grammaire
int error = 0; //erreur renvoyer par chaque sous process
string out = file;
LTerm *tree = new LTerm();
Prog *main;
switch(result) {
case 0 : out = out + "p";
error = preprocess((const char*) file, out.c_str());
if(error) { return error; }
case 1 : lexical_analyser((const char*) argv[1], out.c_str(), tree);
if(error) { return error; }
case 2 : tree = prog_tree(tree);
error = analyse_tree(tree);
if(error) { return error; }
case 3 : main = new Prog(tree);
}
return execute(main, NULL);
}
|
#ifdef SUCK_TREECORE_GEOMETRY
#include "treeface/graphics/guts/GeomSucker.h"
#include "cairo-svg.h"
#include <treecore/Process.h>
#include <treecore/File.h>
#include <treecore/StringRef.h>
#include "treeface/graphics/guts/HalfOutline.h"
#include "treeface/graphics/guts/HalfEdgeNetwork.h"
#include "treeface/math/Constants.h"
using namespace treecore;
namespace treeface
{
GeomSucker::GeomSucker( const HalfEdgeNetwork& network, const treecore::String& title )
: network( network )
{
// get X and Y boundary
float x_min = std::numeric_limits<float>::max();
float y_min = std::numeric_limits<float>::max();
float x_max = std::numeric_limits<float>::min();
float y_max = std::numeric_limits<float>::min();
for (int i = 0; i < network.vertices.size(); i++)
{
const Vec2f& vtx = network.vertices.get<Vec2f>( i );
if (x_min > vtx.x) x_min = vtx.x;
if (y_min > vtx.y) y_min = vtx.y;
if (x_max < vtx.x) x_max = vtx.x;
if (y_max < vtx.y) y_max = vtx.y;
}
// get scales
width = x_max - x_min;
height = y_max - y_min;
line_w = std::sqrt( width * height ) / 200;
// decide output file name
String file_out;
for (int i = 0;; i++)
{
file_out = String( pointer_sized_int( Process::getProcessID() ) ) + "_" + String( i ) + ".svg";
if ( !File::getCurrentWorkingDirectory().getChildFile( file_out ).exists() )
break;
}
// create cairo stuffs
float border = std::min( width * 0.5, height * 0.5 );
surface = cairo_svg_surface_create( file_out.toRawUTF8(), (width + border * 2) * 5, (height + border * 2) * 5 );
context = cairo_create( surface );
// set to initial state
cairo_scale( context, 5, 5 );
cairo_translate( context, border, border );
cairo_translate( context, -x_min, height + y_min );
cairo_set_line_width( context, line_w );
cairo_set_line_cap( context, CAIRO_LINE_CAP_ROUND );
cairo_set_line_join( context, CAIRO_LINE_JOIN_ROUND );
cairo_save( context );
{
//draw axis
cairo_move_to( context, x_min, 0 );
cairo_line_to( context, x_max, 0 );
cairo_move_to( context, 0.0, -y_min );
cairo_line_to( context, 0.0, -y_max );
cairo_set_line_width( context, 2 * line_w );
cairo_set_source_rgba( context, SUCKER_BLACK, 0.4 );
cairo_stroke( context );
// draw skeleton
cairo_set_line_width( context, line_w );
Array<bool> rendered;
rendered.resize( network.edges.size() );
for (int i = 0; i < network.edges.size(); i++) rendered[i] = false;
for (int i_begin = 0; i_begin < network.edges.size(); i_begin++)
{
if (rendered[i_begin]) continue;
cairo_new_path( context );
for (int i_edge = i_begin;; )
{
const HalfEdge& edge = network.edges[i_edge];
const Vec2f& vtx = edge.get_vertex( network.vertices );
cairo_line_to( context, vtx.x, -vtx.y );
rendered[i_edge] = true;
i_edge = edge.idx_next_edge;
if (i_edge == i_begin) break;
}
cairo_close_path( context );
cairo_stroke( context );
}
// draw title
cairo_set_font_size( context, line_w * 8 );
cairo_text_extents_t ext;
cairo_text_extents( context, title.toRawUTF8(), &ext );
cairo_move_to( context, (width - ext.width) / 2, -(height - ext.height) / 2 );
cairo_set_source_rgba( context, 0.0, 0.0, 0.0, 1.0 );
cairo_show_text( context, title.toRawUTF8() );
}
cairo_restore( context );
}
GeomSucker::~GeomSucker()
{
if (context)
cairo_destroy( context );
if (surface)
cairo_surface_destroy( surface );
}
void GeomSucker::draw_vtx( IndexType vtx_idx ) const
{
const Vec2f& vtx = network.vertices.get<Vec2f>( vtx_idx );
draw_vtx( vtx );
}
void GeomSucker::draw_vtx( const Vec2f& vtx ) const
{
cairo_new_path( context );
cairo_arc( context, vtx.x, -vtx.y, line_w * 2, 0, 3.14159265 * 2 );
cairo_fill( context );
}
void GeomSucker::draw_vector( const Vec2f& start, const Vec2f& end ) const
{
cairo_save( context );
cairo_new_path( context );
Vec2f v = end - start;
v.normalize();
float arrow_sz = line_w * 2;
Vec2f ortho( -v.y, v.x );
Vec2f p_arrow_root = end - v * (arrow_sz * 3.0f);
Vec2f p_arrow_root2 = end - v * (arrow_sz * 2.0f);
Vec2f p_arrow1 = p_arrow_root + ortho * arrow_sz;
Vec2f p_arrow2 = p_arrow_root + ortho * -arrow_sz;
cairo_move_to( context, start.x, -start.y );
cairo_line_to( context, end.x, -end.y );
cairo_set_line_width( context, line_w );
cairo_stroke( context );
cairo_move_to( context, end.x, -end.y );
cairo_line_to( context, p_arrow1.x, -p_arrow1.y );
cairo_line_to( context, p_arrow_root2.x, -p_arrow_root2.y );
cairo_line_to( context, p_arrow2.x, -p_arrow2.y );
cairo_fill( context );
cairo_restore( context );
}
void GeomSucker::draw_roled_vtx( IndexType vtx_idx, VertexRole role ) const
{
switch (role)
{
case VTX_ROLE_START: draw_start_vtx( vtx_idx ); break;
case VTX_ROLE_END: draw_end_vtx( vtx_idx ); break;
case VTX_ROLE_LEFT: draw_regular_left_vtx( vtx_idx ); break;
case VTX_ROLE_RIGHT: draw_regular_right_vtx( vtx_idx ); break;
case VTX_ROLE_MERGE: draw_merge_vtx( vtx_idx ); break;
case VTX_ROLE_SPLIT: draw_split_vtx( vtx_idx ); break;
default: abort();
}
}
void GeomSucker::draw_merge_vtx( IndexType vtx_idx ) const
{
const Vec2f& vtx = network.vertices.get<Vec2f>( vtx_idx );
Vec2f p1 = vtx - Vec2f( 0.0f, line_w * 2 );
Vec2f p2 = vtx + Vec2f( line_w * 2, line_w * 2 );
Vec2f p3 = vtx + Vec2f( -line_w * 2, line_w * 2 );
cairo_move_to( context, p1.x, -p1.y );
cairo_line_to( context, p2.x, -p2.y );
cairo_line_to( context, p3.x, -p3.y );
cairo_fill( context );
}
void GeomSucker::draw_split_vtx( IndexType vtx_idx ) const
{
const Vec2f& vtx = network.vertices.get<Vec2f>( vtx_idx );
Vec2f p1 = vtx + Vec2f( 0.0f, line_w * 2 );
Vec2f p2 = vtx + Vec2f( line_w * 2, -line_w * 2 );
Vec2f p3 = vtx + Vec2f( -line_w * 2, -line_w * 2 );
cairo_move_to( context, p1.x, -p1.y );
cairo_line_to( context, p2.x, -p2.y );
cairo_line_to( context, p3.x, -p3.y );
cairo_fill( context );
}
void GeomSucker::draw_start_vtx( IndexType vtx_idx ) const
{
const Vec2f& vtx = network.vertices.get<Vec2f>( vtx_idx );
Vec2f p1 = vtx + Vec2f( line_w * 1.5, line_w * 1.5 );
Vec2f p2 = vtx + Vec2f( -line_w * 1.5, line_w * 1.5 );
Vec2f p3 = vtx + Vec2f( -line_w * 1.5, -line_w * 1.5 );
Vec2f p4 = vtx + Vec2f( line_w * 1.5, -line_w * 1.5 );
cairo_move_to( context, p1.x, -p1.y );
cairo_line_to( context, p2.x, -p2.y );
cairo_line_to( context, p3.x, -p3.y );
cairo_line_to( context, p4.x, -p4.y );
cairo_close_path( context );
cairo_stroke( context );
}
void GeomSucker::draw_end_vtx( IndexType vtx_idx ) const
{
const Vec2f& vtx = network.vertices.get<Vec2f>( vtx_idx );
Vec2f p1 = vtx + Vec2f( line_w * 1.5, line_w * 1.5 );
Vec2f p2 = vtx + Vec2f( -line_w * 1.5, line_w * 1.5 );
Vec2f p3 = vtx + Vec2f( -line_w * 1.5, -line_w * 1.5 );
Vec2f p4 = vtx + Vec2f( line_w * 1.5, -line_w * 1.5 );
cairo_move_to( context, p1.x, -p1.y );
cairo_line_to( context, p2.x, -p2.y );
cairo_line_to( context, p3.x, -p3.y );
cairo_line_to( context, p4.x, -p4.y );
cairo_fill( context );
}
void GeomSucker::draw_regular_left_vtx( IndexType vtx_idx ) const
{
draw_vtx( vtx_idx );
const Vec2f& vtx = network.vertices.get<Vec2f>( vtx_idx );
cairo_new_path( context );
cairo_move_to( context, vtx.x - line_w * 2, -vtx.y - line_w * 5 );
cairo_line_to( context, vtx.x - line_w * 2, -vtx.y + line_w * 5 );
cairo_stroke( context );
}
void GeomSucker::draw_regular_right_vtx( IndexType vtx_idx ) const
{
draw_vtx( vtx_idx );
const Vec2f& vtx = network.vertices.get<Vec2f>( vtx_idx );
cairo_new_path( context );
cairo_move_to( context, vtx.x + line_w * 2, -vtx.y - line_w * 5 );
cairo_line_to( context, vtx.x + line_w * 2, -vtx.y + line_w * 5 );
cairo_stroke( context );
}
void GeomSucker::draw_edge( const IndexType i_edge, float offset_rate ) const
{
const HalfEdge& edge = network.edges[i_edge];
const Vec2f& p_start = edge.get_vertex( network.vertices );
const Vec2f& p_end = edge.get_next( network.edges ).get_vertex( network.vertices );
const Vec2f& p_prev = edge.get_prev( network.edges ).get_vertex( network.vertices );
const Vec2f& p_next = edge.get_next( network.edges ).get_next( network.edges ).get_vertex( network.vertices );
Vec2f v_prev = p_start - p_prev;
Vec2f v_curr = p_end - p_start;
Vec2f v_next = p_next - p_end;
float l_prev = v_prev.normalize();
float l_curr = v_curr.normalize();
float l_next = v_next.normalize();
float offset = line_w * offset_rate;
Vec2f p1 = p_start - v_prev * (l_prev / 3.0f) + v_curr * offset;
Vec2f p2 = p_start + (v_curr - v_prev) * offset;
Vec2f p3 = p_end + (v_next - v_curr) * offset;
Vec2f p4 = p_end + v_next * (l_next / 3.0f) - v_curr * offset;
// arrow
float arrow_sz = line_w * 2;
Vec2f ortho_next( -v_next.y, v_next.x );
Vec2f p_arrow_root = p4 - v_next * (arrow_sz * 3.0f);
Vec2f p_arrow_root2 = p4 - v_next * (arrow_sz * 2.0f);
Vec2f p_arrow1 = p_arrow_root + ortho_next * arrow_sz;
Vec2f p_arrow2 = p_arrow_root + ortho_next * -arrow_sz;
// do_drawing
cairo_new_path( context );
cairo_move_to( context, p1.x, -p1.y );
cairo_line_to( context, p2.x, -p2.y );
cairo_line_to( context, p3.x, -p3.y );
cairo_line_to( context, p4.x, -p4.y );
cairo_set_line_width( context, line_w );
cairo_stroke( context );
cairo_move_to( context, p_arrow1.x, -p_arrow1.y );
cairo_line_to( context, p4.x, -p4.y );
cairo_line_to( context, p_arrow2.x, -p_arrow2.y );
cairo_line_to( context, p_arrow_root2.x, -p_arrow_root2.y );
cairo_fill( context );
draw_vtx( edge.idx_vertex );
}
void GeomSucker::draw_edge_stack( const treecore::Array<IndexType>& edges ) const
{
cairo_save( context );
cairo_set_source_rgba( context, SUCKER_BLACK, 0.3 );
for (IndexType edge_i : edges)
{
draw_edge( edge_i );
}
cairo_restore( context );
}
void GeomSucker::draw_trig_by_edge( IndexType i_edge1, IndexType i_edge2, IndexType i_edge3 ) const
{
const Vec2f& p1 = network.get_edge_vertex( i_edge1 );
const Vec2f& p2 = network.get_edge_vertex( i_edge2 );
const Vec2f& p3 = network.get_edge_vertex( i_edge3 );
cairo_new_path( context );
cairo_move_to( context, p1.x, -p1.y );
cairo_line_to( context, p2.x, -p2.y );
cairo_line_to( context, p3.x, -p3.y );
cairo_fill( context );
}
void GeomSucker::draw_helper( IndexType i_edge, IndexType i_helper ) const
{
cairo_save( context );
draw_edge( i_edge, 1.0f );
cairo_set_source_rgb( context, SUCKER_GREEN );
draw_vtx( i_helper );
cairo_restore( context );
}
void GeomSucker::draw_helper_change( IndexType i_edge, IndexType i_helper_old, IndexType i_helper_new ) const
{
cairo_save( context );
draw_edge( i_edge, 0.5f );
cairo_set_source_rgba( context, SUCKER_BLUE, 0.33 );
draw_edge( i_helper_old, 1.0f );
cairo_set_source_rgba( context, SUCKER_GREEN, 0.66 );
draw_edge( i_helper_new, 2.0f );
cairo_restore( context );
}
void GeomSucker::text( const treecore::String& text, const Vec2f& position ) const
{
cairo_move_to( context, position.x, -position.y );
cairo_set_font_size( context, line_w * 5 );
cairo_show_text( context, text.toRawUTF8() );
}
void GeomSucker::text( const treecore::String& text, IndexType i_vtx ) const
{
this->text( text, network.vertices.get<Vec2f>( i_vtx ) );
}
OutlineSucker::OutlineSucker( const HalfOutline& outline,
const treecore::String& title )
: outline( outline )
{
// get X and Y boundary
float x_min = std::numeric_limits<float>::max();
float y_min = std::numeric_limits<float>::max();
float x_max = std::numeric_limits<float>::min();
float y_max = std::numeric_limits<float>::min();
if (outline.outline.size() > 0)
{
for (const Vec2f& vtx : outline.outline)
{
if (x_min > vtx.x) x_min = vtx.x;
if (y_min > vtx.y) y_min = vtx.y;
if (x_max < vtx.x) x_max = vtx.x;
if (y_max < vtx.y) y_max = vtx.y;
}
}
else
{
x_min = -1.0f;
x_max = 1.0f;
y_min = -1.0f;
y_max = 1.0f;
}
// get scales
{
float content_w = x_max - x_min;
float content_h = y_max - y_min;
if (content_w <= 0.0f) content_w = 2.0f;
if (content_h <= 0.0f) content_h = 2.0f;
if (x_min > -content_w / 5) x_min = -content_w / 5;
if (x_max < content_w / 5) x_max = content_w / 5;
if (y_min > -content_h / 5) y_min = -content_h / 5;
if (y_max < content_h / 5) y_max = content_h / 5;
width = x_max - x_min;
height = y_max - y_min;
}
line_w = std::sqrt( width * height ) / 200;
// decide output file name
String file_out;
for (int i = 0;; i++)
{
file_out = String( pointer_sized_int( Process::getProcessID() ) ) + "_" + String( i ) + ".svg";
if ( !File::getCurrentWorkingDirectory().getChildFile( file_out ).exists() )
break;
}
// create cairo stuffs
float scale = 1.0f;
if (width * height < 40000.0f)
{
scale = sqrt( 40000.0f / width / height );
printf( "too small, enlarge %f\n", scale );
}
float border = std::max( width / 2, height / 2 );
surface = cairo_svg_surface_create( file_out.toRawUTF8(), (width + border * 2) * scale, (height + border * 2) * scale );
context = cairo_create( surface );
// set to initial state
cairo_scale( context, scale, scale );
cairo_translate( context, border, border );
cairo_translate( context, -x_min, height + y_min );
cairo_set_line_width( context, line_w );
cairo_set_line_cap( context, CAIRO_LINE_CAP_ROUND );
cairo_set_line_join( context, CAIRO_LINE_JOIN_ROUND );
cairo_save( context );
{
//draw axis
cairo_move_to( context, x_min, 0 );
cairo_line_to( context, x_max, 0 );
cairo_move_to( context, 0.0, -y_min );
cairo_line_to( context, 0.0, -y_max );
cairo_set_line_width( context, 2 * line_w );
cairo_set_source_rgba( context, SUCKER_BLACK, 0.4 );
cairo_stroke( context );
// draw skeleton
draw_outline( outline );
// draw title
cairo_set_font_size( context, line_w * 8 );
cairo_text_extents_t ext;
cairo_text_extents( context, title.toRawUTF8(), &ext );
cairo_move_to( context, (x_min + x_max - ext.width) / 2, -(y_min + y_max - ext.height) / 2 );
cairo_set_source_rgba( context, 0.0, 0.0, 0.0, 1.0 );
cairo_show_text( context, title.toRawUTF8() );
}
cairo_restore( context );
}
OutlineSucker::~OutlineSucker()
{
if (context)
cairo_destroy( context );
if (surface)
cairo_surface_destroy( surface );
}
void OutlineSucker::draw_vtx( int i_outline ) const
{
draw_vtx( outline.outline[i_outline] );
}
void OutlineSucker::draw_vtx( const Vec2f& vtx ) const
{
cairo_new_path( context );
cairo_arc( context, vtx.x, -vtx.y, line_w * 2, 0, 3.14159265 * 2 );
cairo_fill( context );
}
void OutlineSucker::draw_vector( const Vec2f& start, const Vec2f& end ) const
{
cairo_save( context );
cairo_new_path( context );
Vec2f v = end - start;
v.normalize();
float arrow_sz = line_w * 2;
Vec2f ortho( -v.y, v.x );
Vec2f p_arrow_root = end - v * (arrow_sz * 3.0f);
Vec2f p_arrow_root2 = end - v * (arrow_sz * 2.0f);
Vec2f p_arrow1 = p_arrow_root + ortho * arrow_sz;
Vec2f p_arrow2 = p_arrow_root + ortho * -arrow_sz;
cairo_move_to( context, start.x, -start.y );
cairo_line_to( context, end.x, -end.y );
cairo_set_line_width( context, line_w );
cairo_stroke( context );
cairo_move_to( context, end.x, -end.y );
cairo_line_to( context, p_arrow1.x, -p_arrow1.y );
cairo_line_to( context, p_arrow_root2.x, -p_arrow_root2.y );
cairo_line_to( context, p_arrow2.x, -p_arrow2.y );
cairo_fill( context );
cairo_restore( context );
}
void OutlineSucker::draw_unit_vector( const Vec2f& start, const Vec2f& v ) const
{
Vec2f end = start + v * line_w * 20.0f;
draw_vector( start, end );
}
void OutlineSucker::text( const treecore::String& content, int i_outline ) const
{
draw_vtx( i_outline );
text( content, outline.outline[i_outline] );
}
void OutlineSucker::text( const treecore::String& content, const Vec2f& position ) const
{
cairo_move_to( context, position.x, -position.y );
cairo_set_font_size( context, line_w * 5 );
cairo_show_text( context, content.toRawUTF8() );
}
void OutlineSucker::draw_outline( const HalfOutline& content ) const
{
if (content.outline.size() == 0)
return;
cairo_save( context );
if (content.side > 0) cairo_set_source_rgb( context, SUCKER_ORANGE );
else cairo_set_source_rgb( context, SUCKER_CYAN );
// half outline skeleton
cairo_new_path( context );
cairo_set_line_width( context, line_w );
for (int i = 0; i < content.outline.size(); i++)
{
const Vec2f& p = content.outline[i];
cairo_line_to( context, p.x, -p.y );
}
cairo_stroke( context );
// half outline joint IDs
cairo_save( context );
cairo_set_source_rgba( context, SUCKER_BLACK, 0.5f );
cairo_set_font_size( context, line_w * 5 );
for (int i = 0; i < content.outline.size(); i++)
{
const Vec2f& p = content.outline[i];
cairo_move_to( context, p.x, -p.y );
cairo_show_text( context, String( content.joint_ids[i] ).toRawUTF8() );
}
cairo_restore( context );
// end mark
const Vec2f& last = content.outline.getLast();
float mark_sz = line_w * 5;
cairo_new_path( context );
if (content.sunken)
{
cairo_move_to( context, last.x - mark_sz, -(last.y - mark_sz) );
cairo_line_to( context, last.x + mark_sz, -(last.y + mark_sz) );
cairo_move_to( context, last.x - mark_sz, -(last.y + mark_sz) );
cairo_line_to( context, last.x + mark_sz, -(last.y - mark_sz) );
}
else
{
cairo_arc( context, last.x, -last.y, line_w * 5, 0, treeface::PI * 2 );
cairo_close_path( context );
}
cairo_stroke( context );
cairo_restore( context );
}
void OutlineSucker::draw_trig( const Vec2f& p1, const Vec2f& p2, const Vec2f& p3 ) const
{
cairo_new_path( context );
cairo_move_to( context, p1.x, -p1.y );
cairo_line_to( context, p2.x, -p2.y );
cairo_line_to( context, p3.x, -p3.y );
cairo_fill( context );
}
} // namespace treeface
#endif // SUCK_TREECORE_GEOMETRY
|
#pragma once
#include <SFML/Graphics.hpp>
class Window{
public:
static sf::Image image;
static sf::RenderWindow window;
};
|
#include "simexamples/SimFramework.h"
#include "include/SimException.h"
#include "SimExamples/triangle/ExmTriangle.h"
#include "SimExamples/voronoi/ExmVoronoi.h"
int WINAPI
WinMain( __in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in LPSTR lpCmdLine, __in int nShowCmd )
{
try {
//SIM_EXCEPTION("ERROR");
/*ExmTriangle* app = new ExmTriangle(hInstance, "simroot.ini");*/
ExmVoronoi* app = new ExmVoronoi(hInstance, "simroot.ini");
app->Run();
}catch(const sim::Exception& e){
MessageBox(NULL,
e.what(), "Sim - Error", /*MB_OKCANCEL*/MB_ABORTRETRYIGNORE | MB_ICONERROR);
}
return 0;
}
|
#include<cstdio>
using namespace std;
int n,k;
bool zhi[10010]={1,1};
int main()
{
scanf("%d%d",&n,&k);
for(int i=2;i<=n;i++)
for(int j=2;j<=n/i;j++)
zhi[i*j]=1;
int flag=0;
for(int i=2;i<=n-k;i++)
{
int j=i+k;
if(!zhi[i] && !zhi[j])
{
printf("%d %d\n",i,j);
flag=1;
}
}
if(!flag) printf("empty");
}
|
class PartFueltank : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "\dayz_equip\models\fueltank.p3d";
picture = "\dayz_equip\textures\equip_fueltank_ca.paa";
displayName = $STR_EQUIP_NAME_8;
descriptionShort = $STR_EQUIP_DESC_8;
class ItemActions
{
class Crafting
{
text = $STR_EPOCH_PLAYER_212;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox","ItemCrowbar"};
output[] = {{"PartGeneric",1}};
input[] = {{"PartFueltank",1}};
};
};
};
class PartWheel : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "\dayz_equip\models\wheel.p3d";
picture = "\dayz_equip\textures\equip_wheel_ca.paa";
displayName = $STR_EQUIP_NAME_9;
descriptionShort = $STR_EQUIP_DESC_9;
};
class PartEngine : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "\dayz_equip\models\engine.p3d";
picture = "\dayz_equip\textures\equip_engine_ca.paa";
displayName = $STR_EQUIP_NAME_11;
descriptionShort = $STR_EQUIP_DESC_11;
class ItemActions
{
class Crafting
{
text = $STR_EPOCH_PLAYER_212;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox","ItemCrowbar"};
output[] = {{"PartGeneric",2}};
input[] = {{"PartEngine",1}};
};
};
};
class PartVRotor : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "\dayz_equip\models\vrotor.p3d";
picture = "\dayz_equip\textures\equip_vrotor_ca.paa";
displayName = $STR_EQUIP_NAME_32;
descriptionShort = $STR_EQUIP_DESC_32;
class ItemActions
{
class Crafting
{
text = $STR_EPOCH_PLAYER_212;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox","ItemCrowbar"};
output[] = {{"PartGeneric",3}};
input[] = {{"PartVRotor",1}};
};
};
};
class PartGlass : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "\dayz_equip\models\carglass.p3d";
picture = "\dayz_equip\textures\equip_carglass_ca.paa";
displayName = $STR_EQUIP_NAME_30;
descriptionShort = $STR_EQUIP_DESC_30;
class ItemActions
{
class Crafting
{
text = $STR_EPOCH_ACTION_GLASS_FLOOR_QUARTER;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox","ItemCrowbar"};
output[] = {{"glass_floor_quarter_kit",1}};
input[] = {{"ItemPole",4},{"PartGlass",4}};
};
};
};
class PartFueltankBroken : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "\dayz_equip\models\fueltank.p3d";
picture = "\dayz_epoch_c\icons\vehicleparts\equip_fueltank_broken_ca";
displayName = $STR_EPOCH_BROKEN_FUELTANK;
descriptionShort = $STR_EPOCH_BROKEN_FUELTANK_DESC;
class ItemActions
{
class Crafting
{
text = $STR_EPOCH_PLAYER_212;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox","ItemCrowbar"};
output[] = {{"PartGeneric",1}};
input[] = {{"PartFueltankBroken",1}};
};
};
};
class PartWheelBroken : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "\dayz_equip\models\wheel.p3d";
picture = "\dayz_epoch_c\icons\vehicleparts\equip_wheel_broken_ca.paa";
displayName = $STR_EPOCH_BROKEN_CARWHEEL;
descriptionShort = $STR_EPOCH_BROKEN_CARWHEEL_DESC;
};
class PartEngineBroken : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "\dayz_equip\models\engine.p3d";
picture = "\dayz_epoch_c\icons\vehicleparts\equip_engine_broken_ca.paa";
displayName = $STR_EPOCH_BROKEN_ENGINEPARTS;
descriptionShort = $STR_EPOCH_BROKEN_ENGINEPARTS_DESC;
class ItemActions
{
class Crafting
{
text = $STR_EPOCH_PLAYER_212;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox","ItemCrowbar"};
output[] = {{"PartGeneric",2}};
input[] = {{"PartEngineBroken",1}};
};
};
};
class PartVRotorBroken : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "\dayz_equip\models\vrotor.p3d";
picture = "\dayz_epoch_c\icons\vehicleparts\equip_vrotor_broken_ca.paa";
displayName = $STR_EPOCH_BROKEN_ROTOR;
descriptionShort = $STR_EPOCH_BROKEN_ROTOR_DESC;
class ItemActions
{
class Crafting
{
text = $STR_EPOCH_PLAYER_212;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {"workshop"};
requiretools[] = {"ItemToolbox","ItemCrowbar"};
output[] = {{"PartGeneric",3}};
input[] = {{"PartVRotorBroken",1}};
};
};
};
class PartGlassBroken : CA_Magazine
{
scope = 2;
count = 1;
type = 256;
model = "\dayz_equip\models\carglass.p3d";
picture = "\dayz_epoch_c\icons\vehicleparts\equip_carglass_broken_CA.paa";
displayName = $STR_EPOCH_BROKEN_GLASS;
descriptionShort = $STR_EPOCH_BROKEN_GLASS_DESC;
};
// PartGeneric can be found under Items\Metal.hpp
|
// Created on: 1997-03-03
// Created by: Yves FRICAUD
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TNaming_Identifier_HeaderFile
#define _TNaming_Identifier_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TDF_Label.hxx>
#include <TNaming_NameType.hxx>
#include <TNaming_ListOfNamedShape.hxx>
#include <TopTools_ListOfShape.hxx>
class TNaming_NamedShape;
class TNaming_Localizer;
class TNaming_Identifier
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT TNaming_Identifier(const TDF_Label& Lab, const TopoDS_Shape& S, const TopoDS_Shape& Context, const Standard_Boolean Geom);
Standard_EXPORT TNaming_Identifier(const TDF_Label& Lab, const TopoDS_Shape& S, const Handle(TNaming_NamedShape)& ContextNS, const Standard_Boolean Geom);
Standard_EXPORT Standard_Boolean IsDone() const;
Standard_EXPORT TNaming_NameType Type() const;
Standard_EXPORT Standard_Boolean IsFeature();
Standard_EXPORT Handle(TNaming_NamedShape) Feature() const;
Standard_EXPORT void InitArgs();
Standard_EXPORT Standard_Boolean MoreArgs() const;
Standard_EXPORT void NextArg();
Standard_EXPORT Standard_Boolean ArgIsFeature() const;
Standard_EXPORT Handle(TNaming_NamedShape) FeatureArg();
Standard_EXPORT TopoDS_Shape ShapeArg();
Standard_EXPORT TopoDS_Shape ShapeContext() const;
Standard_EXPORT Handle(TNaming_NamedShape) NamedShapeOfGeneration() const;
Standard_EXPORT void AncestorIdentification (TNaming_Localizer& Localizer, const TopoDS_Shape& Context);
Standard_EXPORT void PrimitiveIdentification (TNaming_Localizer& Localizer, const Handle(TNaming_NamedShape)& NS);
Standard_EXPORT void GeneratedIdentification (TNaming_Localizer& Localizer, const Handle(TNaming_NamedShape)& NS);
Standard_EXPORT void Identification (TNaming_Localizer& Localizer, const Handle(TNaming_NamedShape)& NS);
protected:
private:
Standard_EXPORT void Init (const TopoDS_Shape& Context);
TDF_Label myTDFAcces;
TopoDS_Shape myShape;
Standard_Boolean myDone;
Standard_Boolean myIsFeature;
TNaming_NameType myType;
Handle(TNaming_NamedShape) myFeature;
TNaming_ListOfNamedShape myPrimitiveArgs;
TopTools_ListOfShape myShapeArgs;
Handle(TNaming_NamedShape) myNSContext;
};
#endif // _TNaming_Identifier_HeaderFile
|
//
// Created by Brady Bodily on 4/22/17.
//
#ifndef ITAK_KEYCOUNT_HPP
#define ITAK_KEYCOUNT_HPP
class KeyCount {
private:
int Key;
int Count;
public:
KeyCount(int key){Key = key; Count = 1;}
int GetKey(){return Key;}
int GetCount(){return Count;}
void SetKey(int key){Key = key;}
void IncrementCount(){Count++;}
};
#endif //ITAK_KEYCOUNT_HPP
|
#include "spi.h"
#include <stdio.h>
//#include "cterm/ctermcore.h"
//---- cfiler_native.cpp から流用+α
#ifdef DEBUG
struct FuncTrace
{
FuncTrace( const char * _funcname, unsigned int _lineno )
{
funcname = _funcname;
lineno = _lineno;
printf( "FuncTrace : Enter : %s(%)\n", funcname, lineno );
}
~FuncTrace()
{
printf( "FuncTrace : Leave : %s(%)\n", funcname, lineno );
}
const char * funcname;
unsigned int lineno;
};
#define FUNC_TRACE FuncTrace functrace(__FUNCTION__,__LINE__)
#define _TRACE(...) printf(__VA_ARGS__)
#else
#define FUNC_TRACE
#define _TRACE(...) ((void)0)
#endif
//---- cfiler_native.cpp から流用+α
//---- from pythonutil.hから流用
namespace StringUtil
{
std::wstring MultiByteToWideChar( const char * str, int len );
std::string WideCharToMultiByte( const wchar_t * str, int len );
};
std::wstring StringUtil::MultiByteToWideChar( const char * str, int len )
{
int buf_size = len+2;
wchar_t * buf = new wchar_t[ buf_size ];
int write_len = ::MultiByteToWideChar( 0, 0, str, len, buf, buf_size );
buf[write_len] = '\0';
std::wstring ret = buf;
delete [] buf;
return ret;
}
std::string StringUtil::WideCharToMultiByte( const wchar_t * str, int len )
{
int buf_size = len*2+2;
char * buf = new char[ buf_size ];
int write_len = ::WideCharToMultiByte( 0, 0, str, len, buf, buf_size, NULL, NULL );
buf[write_len] = '\0';
std::string ret = buf;
delete [] buf;
return ret;
}
//---- Python2.7
// bool PythonUtil::PyStringToString( const PyObject * pystr, std::string * str )
// {
// if( PyUnicode_Check(pystr) )
// {
// *str = StringUtil::WideCharToMultiByte( (const wchar_t*)PyUnicode_AS_UNICODE(pystr), PyUnicode_GET_SIZE(pystr) );
// return true;
// }
// else if( PyString_Check(pystr) )
// {
// *str = PyString_AS_STRING(pystr);
// return true;
// }
// else
// {
// PyErr_SetString( PyExc_TypeError, "must be string or unicode." );
// *str = "";
// return false;
// }
// }
//
// bool PythonUtil::PyStringToWideString( const PyObject * pystr, std::wstring * str )
// {
// if( PyUnicode_Check(pystr) )
// {
// *str = (wchar_t*)PyUnicode_AS_UNICODE(pystr);
// return true;
// }
// else if( PyString_Check(pystr) )
// {
// *str = StringUtil::MultiByteToWideChar( (const char*)PyString_AS_STRING(pystr), PyString_GET_SIZE(pystr) );
// return true;
// }
// else
// {
// PyErr_SetString( PyExc_TypeError, "must be string or unicode." );
// *str = L"";
// return false;
// }
// }
bool PythonUtil::PyStringToString( const PyObject * pystr, std::string * str )
{
if( PyUnicode_Check(pystr) )
{
*str = StringUtil::WideCharToMultiByte( (const wchar_t*)PyUnicode_AS_UNICODE(pystr), PyUnicode_GET_SIZE(pystr) );
return true;
}
else
{
PyErr_SetString( PyExc_TypeError, "must be string or unicode." );
*str = "";
return false;
}
}
bool PythonUtil::PyStringToWideString( const PyObject * pystr, std::wstring * str )
{
if( PyUnicode_Check(pystr) )
{
*str = (wchar_t*)PyUnicode_AS_UNICODE(pystr);
return true;
}
else
{
PyErr_SetString( PyExc_TypeError, "must be string or unicode." );
*str = L"";
return false;
}
}
//---- from pythonutil.hから流用
CSPI::CSPI() :
ref_count(0),
_hDll(0),
_funcGetPluginInfo (NULL),
_funcIsSupported (NULL),
_funcGetPictureInfo (NULL),
_funcGetPicture (NULL)
{
}
CSPI::~CSPI()
{
term();
}
int CSPI::loadDll(const WCHAR *dll_fname)
{
if(_hDll) term();
_hDll = ::LoadLibrary(dll_fname);
if(_hDll == NULL)
{
// ロード失敗
return 0;
}
_funcGetPluginInfo = reinterpret_cast<GET_PLUGIN_INFO >(::GetProcAddress(_hDll, "GetPluginInfo"));
_funcIsSupported = reinterpret_cast<IS_SUPPORTED >(::GetProcAddress(_hDll, "IsSupported"));
_funcGetPictureInfo = reinterpret_cast<GET_PICTURE_INFO>(::GetProcAddress(_hDll, "GetPictureInfo"));
_funcGetPicture = reinterpret_cast<GET_PICTURE >(::GetProcAddress(_hDll, "GetPicture"));
// 関数取得できない
if(_funcGetPluginInfo == NULL ||
_funcIsSupported == NULL ||
_funcGetPictureInfo == NULL ||
_funcGetPicture == NULL)
return 0;
return 1;
}
void CSPI::term()
{
_TRACE("CSPI::term\n");
if(_hDll)
{
_TRACE(" free DLL\n");
FreeLibrary(_hDll);
_hDll = NULL;
}
}
// GetPluginInfo系
bool CSPI::getPluginInfoAPIVer(std::string *s)
{
int ret;
char buf[256+1];
if(_funcGetPluginInfo)
{
ret = _funcGetPluginInfo(0, buf, 256);
if(ret)
{
*s = buf;
return true;
}
}
return false;
}
bool CSPI::getPluginInfoAbout (std::string *s)
{
int ret;
char buf[256+1];
if(_funcGetPluginInfo)
{
ret = _funcGetPluginInfo(1, buf, 256);
if(ret)
{
*s = buf;
return true;
}
}
return false;
}
bool CSPI::getPluginInfoExt (int no, std::string *s)
{
int ret;
char buf[256+1];
if(_funcGetPluginInfo)
{
ret = _funcGetPluginInfo(2 + no * 2, buf, 256);
if(ret)
{
*s = buf;
return true;
}
}
return false;
}
// IsSupported系
bool CSPI::isSupported(LPCSTR filename)
{
int ret;
unsigned char buf[1024*2];
if(_funcIsSupported)
{
FILE *fp = fopen(filename, "rb");
if(fp == NULL) return false;
long read_len = fread(buf, 1, sizeof(buf), fp);
if(read_len < sizeof(buf)) memset(buf + read_len, 0, sizeof(buf)-read_len);
fclose(fp);
ret = _funcIsSupported(NULL, (DWORD)buf);
return ret ? true : false;
}
return false;
}
bool CSPI::isSupportedMem(const void *fimg)
{
int ret;
if(_funcIsSupported)
{
ret = _funcIsSupported(NULL, (DWORD)fimg);
return ret ? true : false;
}
return false;
}
// GetPictureInfo系
bool CSPI::getPictureInfo(LPCSTR filename, PictureInfo *info)
{
int ret;
if(_funcGetPictureInfo)
{
ret = _funcGetPictureInfo((LPSTR)filename, 0, 0, info);
return ret == 0 ? true : false;
}
return false;
}
bool CSPI::getPictureInfoMem(const void *fimg, unsigned long size, PictureInfo *info)
{
int ret;
if(_funcGetPictureInfo)
{
ret = _funcGetPictureInfo((CHAR*)fimg, size, 1, info);
return ret == 0 ? true : false;
}
return false;
}
// GetPicture系
bool CSPI::getPicture(LPCSTR filename, HLOCAL *hbminfo, HLOCAL *hbm)
{
int ret;
HLOCAL hbi = NULL, hb = NULL;
if(_funcGetPicture)
{
ret = _funcGetPicture((LPSTR)filename, 0, 0, &hbi, &hb, NULL, 0);
if(ret != 0 || hbminfo == NULL || hbm == NULL)
{
if(hbi) LocalFree(hbi);
if(hb) LocalFree(hb);
return false;
}
*hbminfo = hbi;
*hbm = hb;
return true;
}
return false;
}
bool CSPI::getPictureMem(const void *fimg, unsigned long size, HLOCAL *hbminfo, HLOCAL *hbm)
{
int ret;
HLOCAL hbi = NULL, hb = NULL;
if(_funcGetPicture)
{
ret = _funcGetPicture((CHAR*)fimg, size, 1, &hbi, &hb, NULL, 0);
if(ret != 0 || hbminfo == NULL || hbm == NULL)
{
if(hbi) LocalFree(hbi);
if(hb) LocalFree(hb);
return false;
}
*hbminfo = hbi;
*hbm = hb;
return true;
}
return false;
}
/*
void CSPI::test()
{
int ret;
char buf[256+1];
if(_funcGetPluginInfo)
{
int no = 0;
while((ret = _funcGetPluginInfo(no, buf, 256)) != 0)
{
printf("%d ret=%d %s\n", no, ret, buf);
no++;
}
}
else
{
printf("_funcGetPluginInfo=%p\n", _funcGetPluginInfo);
}
}
*/
//-----------------------------------------------------------------------------
// Pythonインターフェース実装
// cfilerのソースとPythonヘルプ見ながら見よう見まね
static PyObject * SPI_fromPath( PyObject * self, PyObject * args )
{
FUNC_TRACE;
PyObject * pyfilename;
if( ! PyArg_ParseTuple(args, "O", &pyfilename ) )
return NULL;
std::wstring filename;
if( !PythonUtil::PyStringToWideString( pyfilename, &filename ) )
{
return NULL;
}
CSPI *spi = new CSPI;
int ret = spi->loadDll(filename.c_str());
if(ret == 0)
{
delete spi;
std::string msg;
if( !PythonUtil::PyStringToString( pyfilename, &msg ) )
{
return NULL;
}
msg += ": spi load error.";
PyErr_SetString( PyExc_ValueError, msg.c_str() );
return NULL;
}
SPI_Object * pyspi;
pyspi = PyObject_New( SPI_Object, &SPI_Type );
pyspi->p = spi;
spi->AddRef();
return (PyObject*)pyspi;
}
static PyObject * SPI_getExtList( PyObject * self, PyObject * args )
{
FUNC_TRACE;
if( ! PyArg_ParseTuple(args, "" ) )
return NULL;
CSPI *spi = ((SPI_Object*)self)->p;
if( ! spi )
{
PyErr_SetString( PyExc_ValueError, "already destroyed." );
return NULL;
}
std::string ext_list, ext;
const char *delim = ";";
int no = 0;
while(spi->getPluginInfoExt(no, &ext))
{
if(ext_list.length()) ext_list += delim;
ext_list += ext;
no++;
}
// あえて文字列で返す。文字列のほうがマッチング楽なこともあるかも…。
PyObject * pyret = Py_BuildValue( "s", ext_list.c_str() );
return pyret;
}
void __log(const char *fmt, ...)
{
FILE *fp = fopen("log.txt", "wt+");
va_list args;
va_start(args, fmt);
vfprintf(fp, fmt, args);
va_end(args);
fclose(fp);
}
// Imageオブジェクトを作るのが困難なので、サイズ返せるようにする
// ((w,h),depth) = getSize(filename)
static PyObject * SPI_getSizeDepth( PyObject * self, PyObject * args )
{
PyObject *pyfilename;
if( ! PyArg_ParseTuple(args, "O", &pyfilename ) )
return NULL;
CSPI *spi = ((SPI_Object*)self)->p;
std::string filename;
if( !PythonUtil::PyStringToString( pyfilename, &filename ) )
{
return NULL;
}
if(!spi->isSupported(filename.c_str()))
{
PyErr_SetString( PyExc_ValueError, "not supported image." );
return NULL;
}
PictureInfo pi;
pi.hInfo = NULL;
if(!spi->getPictureInfo(filename.c_str(), &pi))
{
PyErr_SetString( PyExc_ValueError, "can't get pictureinfo." );
return NULL;
}
// 一応解放
if(pi.hInfo) LocalFree(pi.hInfo);
// タプルを返す
return Py_BuildValue( "(ii)i", pi.width, pi.height, pi.colorDepth );
}
// ((w,h),depth) = getSize(fileimage)
static PyObject * SPI_getSizeDepthMem( PyObject * self, PyObject * args )
{
const char *fimg;
unsigned int fimg_size;
if( ! PyArg_ParseTuple(args, "s#", &fimg, &fimg_size ) )
return NULL;
CSPI *spi = ((SPI_Object*)self)->p;
if(!spi->isSupportedMem(fimg))
{
PyErr_SetString( PyExc_ValueError, "not supported image." );
return NULL;
}
PictureInfo pi;
pi.hInfo = NULL;
if(!spi->getPictureInfoMem(fimg, fimg_size, &pi))
{
PyErr_SetString( PyExc_ValueError, "can't get pictureinfo." );
return NULL;
}
// 一応解放
if(pi.hInfo) LocalFree(pi.hInfo);
// タプルを返す
return Py_BuildValue( "(ii)i", pi.width, pi.height, pi.colorDepth );
}
static void *_dib2rgba(BITMAPINFO *info, void *src_, unsigned long *pdst_size)
{
int w = info->bmiHeader.biWidth, h = info->bmiHeader.biHeight;
int dst_size = 4 * w * h;
if(pdst_size) *pdst_size = dst_size;
unsigned char *dst = (unsigned char*)malloc(dst_size);
// _TRACE("biSize =%d\n", info->bmiHeader.biSize );
// _TRACE("biWidth =%d\n", info->bmiHeader.biWidth );
// _TRACE("biHeight =%d\n", info->bmiHeader.biHeight );
// _TRACE("biPlanes =%d\n", info->bmiHeader.biPlanes );
// _TRACE("biBitCount =%d\n", info->bmiHeader.biBitCount );
// _TRACE("biCompression =%d\n", info->bmiHeader.biCompression );
// _TRACE("biSizeImage =%d\n", info->bmiHeader.biSizeImage );
// _TRACE("biXPelsPerMeter =%d\n", info->bmiHeader.biXPelsPerMeter );
// _TRACE("biYPelsPerMeter =%d\n", info->bmiHeader.biYPelsPerMeter );
// _TRACE("biClrUsed =%d\n", info->bmiHeader.biClrUsed );
// _TRACE("biClrImportant =%d\n", info->bmiHeader.biClrImportant );
// BMPのストライドは4バイト境界である必要があった気がする
typedef unsigned long u32;
typedef unsigned char u8;
u8 *src = (u8*)src_;
// ビット数変換 まじめに作るとキリないので超適当
switch(info->bmiHeader.biBitCount)
{
case 32:
{
u32 *dst_u32 = (u32*)dst;
for( u32*src_u32 = (u32*)src, *src_end = src_u32 + (w * h);
src_u32 != src_end; src_u32++ ) // 4バイト境界が保証される
{
// BGRA => RGBA
u32 c = *src_u32;
*dst_u32 =
((c & 0x000000FF) << 16) | // B
(c & 0x0000FF00) | // G
((c & 0x00FF0000) >> 16) | // R
(c & 0xFF000000);
dst_u32++;
src_u32++;
}
}
break;
case 24:
// src=24bit
{
int wb = w * 3;
wb = (wb + 3) & (~3); // 4バイト境界
u32 *dst_u32 = (u32*)dst;
for( int yy = h-1;yy>=0;yy-- )
{
u8 *src_u8 = src + (yy*wb);
for( int x=0 ; x<w ; x++ )
{
// BGRx => RGBA
u32 c = *((u32*)src_u8); // x86はアドレスが境界でなくても大丈夫だったはず
*dst_u32 =
((c & 0x000000FF) << 16) | // B
(c & 0x0000FF00) | // G
((c & 0x00FF0000) >> 16) | // R
0xFF000000;
dst_u32++;
src_u8 += 3;
}
}
}
break;
case 8:
{
// 先にパレットの並びを置換
int plt_num = info->bmiHeader.biClrUsed;
if(plt_num == 0) plt_num = 256; // 0なことがある…
u32 *plt =(u32*)malloc(sizeof(u32)*plt_num);
{
u32 *src_plt = (u32*)info->bmiColors;
for(u32 *p = plt, *p_end = plt + plt_num; p != p_end; p++, src_plt++)
{
u32 c = *src_plt;
*p = ((c & 0x000000FF) << 16) | // B
c & 0x0000FF00 | // G
((c & 0x00FF0000) >> 16) | // R
0xFF000000;
}
}
int wb = w;
wb = (w + 3) & (~3); // 4バイト境界
u32 *dst_u32 = (u32*)dst;
for( int yy = h-1;yy>=0;yy-- )
{
u8 *src_u8 = src + (yy*wb);
for( int x=0 ; x<w ; x++ )
{
*dst_u32 = plt[*src_u8];
dst_u32++;
src_u8++;
}
}
free(plt);
}
break;
case 4:
{
// 先にパレットの並びを置換
int plt_num = info->bmiHeader.biClrUsed;
if(plt_num == 0) plt_num = 16; // 0なことがある…
u32 *plt =(u32*)malloc(sizeof(u32)*plt_num);
{
u32 *src_plt = (u32*)info->bmiColors;
for(u32 *p = plt, *p_end = plt + plt_num; p != p_end; p++, src_plt++)
{
u32 c = *src_plt;
*p = ((c & 0x000000FF) << 16) | // B
c & 0x0000FF00 | // G
((c & 0x00FF0000) >> 16) | // R
0xFF000000;
}
}
int aw = (w+1) & (~1); // タプル数をバイト境界にあわせるためアライン2
int wh = aw / 2; // バイト数算出
int wb = wh; // ストライド
wb = (wb + 3) & (~3); // 4バイト境界
// __log("w=%d aw=%d wh=%d wb=%d\n", w, aw, wh, wb);
u32 *dst_u32 = (u32*)dst;
for( int yy = h-1;yy>=0;yy-- )
{
u8 *src_u8 = src + (yy*wb);
for( int x=0 ; x<wh ; x++ )
{
u8 c = *src_u8++;
*dst_u32 = plt[c >> 4];
dst_u32++;
*dst_u32 = plt[c & 0x0F];
dst_u32++;
}
}
}
break;
// ToDo: 1bit, 2bit
}
return dst;
}
// string = loadImage(filename)
static PyObject * SPI_loadImage( PyObject * self, PyObject * args )
{
PyObject *pyfilename;
if( ! PyArg_ParseTuple(args, "O", &pyfilename ) )
return NULL;
CSPI *spi = ((SPI_Object*)self)->p;
std::string filename;
if( !PythonUtil::PyStringToString( pyfilename, &filename ) )
{
return NULL;
}
if(!spi->isSupported(filename.c_str()))
{
PyErr_SetString( PyExc_ValueError, "not supported image." );
return NULL;
}
HLOCAL hbminfo = NULL, hbm = NULL;
if(!spi->getPicture(filename.c_str(), &hbminfo, &hbm))
{
if(hbminfo) LocalFree(hbminfo);
if(hbm) LocalFree(hbm);
PyErr_SetString( PyExc_ValueError, "load error." );
return NULL;
}
BITMAPINFO *info = (BITMAPINFO*)LocalLock(hbminfo);
unsigned char *src = (unsigned char*)LocalLock(hbm);
_TRACE("bitcount=%d\n", info->bmiHeader.biBitCount);
unsigned long dst_size;
void *dst = _dib2rgba(info, src, &dst_size);
PyObject *ret = Py_BuildValue("y#", dst, dst_size);
free(dst);
if(hbminfo) LocalFree(hbminfo);
if(hbm) LocalFree(hbm);
return ret;
}
// string = loadImageFromStr(fileimage)
static PyObject * SPI_loadImageMem( PyObject * self, PyObject * args )
{
const char *fimg;
unsigned int fimg_size;
if( ! PyArg_ParseTuple(args, "s#", &fimg, &fimg_size ) )
return NULL;
CSPI *spi = ((SPI_Object*)self)->p;
if(!spi->isSupportedMem(fimg))
{
PyErr_SetString( PyExc_ValueError, "not supported image." );
return NULL;
}
HLOCAL hbminfo = NULL, hbm = NULL;
if(!spi->getPictureMem(fimg, fimg_size, &hbminfo, &hbm))
{
if(hbminfo) LocalFree(hbminfo);
if(hbm) LocalFree(hbm);
PyErr_SetString( PyExc_ValueError, "load error." );
return NULL;
}
BITMAPINFO *info = (BITMAPINFO*)LocalLock(hbminfo);
unsigned char *src = (unsigned char*)LocalLock(hbm);
_TRACE("bitcount=%d\n", info->bmiHeader.biBitCount);
unsigned long dst_size;
void *dst = _dib2rgba(info, src, &dst_size);
PyObject *ret = Py_BuildValue("y#", dst, dst_size);
free(dst);
if(hbminfo) LocalFree(hbminfo);
if(hbm) LocalFree(hbm);
return ret;
}
static void SPI_dealloc(PyObject* self)
{
FUNC_TRACE;
CSPI * spi = ((SPI_Object*)self)->p;
spi->Release();
self->ob_type->tp_free(self);
}
static PyMethodDef SPI_methods[] = {
{ "getSizeDepth", SPI_getSizeDepth, METH_VARARGS, "" },
{ "loadImage", SPI_loadImage, METH_VARARGS, "" },
{ "getSizeDepthMem",SPI_getSizeDepthMem,METH_VARARGS, "" },
{ "loadImageMem", SPI_loadImageMem, METH_VARARGS, "" },
{ "getExtList", SPI_getExtList, METH_VARARGS, "" },
{ "fromPath", SPI_fromPath, METH_STATIC|METH_VARARGS, "" },
{NULL, NULL, 0, NULL}
};
PyTypeObject SPI_Type = {
PyObject_HEAD_INIT(NULL)
"SPI", /* tp_name */
sizeof(SPI_Object), /* tp_basicsize */
0, /* tp_itemsize */
SPI_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr,/* tp_getattro */
PyObject_GenericSetAttr,/* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,/* tp_flags */
"", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
SPI_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
0, /* tp_free */
};
#define MODULE_NAME "spi"
static PyMethodDef spi_funcs[] =
{
{NULL, NULL, 0, NULL}
};
static PyModuleDef spi_module =
{
PyModuleDef_HEAD_INIT,
MODULE_NAME,
"spi module.",
-1,
spi_funcs,
NULL, NULL, NULL, NULL
};
static PyObject * Error;
//extern "C" void __stdcall initspi(void)
extern "C" PyMODINIT_FUNC PyInit_spi(void)
{
if( PyType_Ready(&SPI_Type)<0 ) return NULL;
PyObject *m, *d;
// m = Py_InitModule3( MODULE_NAME, cterm_funcs, "spi module." );
m = PyModule_Create(&spi_module);
if(m == NULL) return NULL;
Py_INCREF(&SPI_Type);
PyModule_AddObject( m, "SPI", (PyObject*)&SPI_Type );
d = PyModule_GetDict(m);
Error = PyErr_NewException( MODULE_NAME ".Error", NULL, NULL);
PyDict_SetItemString( d, "Error", Error );
if( PyErr_Occurred() )
{
Py_FatalError( "can't initialize module " MODULE_NAME );
}
return m;
}
|
/******<CODE NEVER DIE>******/
#include<bits/stdc++.h>
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(ll 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**********/
string a,b;
/**********DTL**********/
string Sum(){
while(a.size()<b.size()) a="0"+a;
while(a.size()>b.size()) b="0"+b;
int len=a.size();
string res="";
ll cong=0;
FORD(i,0,len-1){
ll x=ll(a[i]-'0')+ll(b[i]-'0')+cong;
res=char(x%10+'0')+res;
cong=x/10;
}
if(cong>0) return char(cong+'0')+res;
return res;
}
/**********main function**********/
int main(){
FastIO; IN; OUT;
int test;
cin >> test;
while(test--){
cin >> a >> b;
FOR(i,0,a.size()){
if(a[i]=='6') a[i]='5';
}
FOR(i,0,b.size()){
if(b[i]=='6') b[i]='5';
}
cout << Sum() << " ";
FOR(i,0,a.size()){
if(a[i]=='5') a[i]='6';
}
FOR(i,0,b.size()){
if(b[i]=='5') b[i]='6';
}
cout << Sum() << endl;
}
return 0;
}
|
#include <bits/stdc++.h>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
using namespace std;
void dfs(int x, vector< vector<int> >& g, vector<int>& v) {
set<int> w;
for (int i = 0; i < (int)g[x].size(); ++i) {
dfs(g[x][i], g, v);
w.insert(v[g[x][i]]);
}
v[x] = 1;
while (w.count(v[x])) ++v[x];
}
void F(int x, vector< vector<int> >& g, vector< vector<int> >& f) {
for (int i = 0; i < (int)g[x].size(); ++i) {
F(g[x][i], g, f);
}
for (int val = 1; val <= 20; ++val) {
int& total = f[x][val] = val;
for (int i = 0; i < (int)g[x].size(); ++i) {
int mi = 1e9;
for (int j = 1; j <= 20; ++j)
if (j != val && f[g[x][i]][j] < mi)
mi = f[g[x][i]][j];
total += mi;
}
}
}
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
ios::sync_with_stdio(false);
int T;
cin >> T;
vector< vector<int> > g;
vector< vector<int> > f;
for (int __case = 1; __case <= T; ++__case) {
int n;
cin >> n;
g.assign(n + 1, vector<int>());
f.assign(n + 1, vector<int>(21));
for (int i = 1; i <= n; ++i) {
int x;
cin >> x;
g[x].push_back(i);
}
//dfs(1, g, v);
//int pseudoans = accumulate(v.begin(), v.end(), 0);
F(1, g, f);
int ans = *min_element(f[1].begin() + 1, f[1].end());
cout << "Case #" << __case << ": " << ans << endl;
//cerr << __case << endl;
//cerr << ans << " " << pseudoans << endl;
//assert(ans <= pseudoans);
}
return 0;
}
|
/****************************************************************************
**
** Copyright (C) 2005-2008 Trolltech ASA. All rights reserved.
**
** This file is part of the example classes of the Qt Toolkit.
**
** Licensees holding a valid Qt License Agreement may use this file in
** accordance with the rights, responsibilities and obligations
** contained therein. Please consult your licensing agreement or
** contact sales@trolltech.com if any conditions of this licensing
** agreement are not clear to you.
**
** Further information about Qt licensing is available at:
** http://www.trolltech.com/products/qt/licensing.html or by
** contacting info@trolltech.com.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include <QtGui>
#include <QSlider>
#include <QLayout>
#include "glwidget.h"
#include "window.h"
Window::Window(QWidget*parent)
: QWidget(parent)
{
glWidget = new GLWidget(this);
xSlider = createSlider();
ySlider = createSlider();
zSlider = createSlider();
connect(xSlider, SIGNAL(valueChanged(int)), glWidget, SLOT(setXRotation(int)));
connect(glWidget, SIGNAL(xRotationChanged(int)), xSlider, SLOT(setValue(int)));
connect(ySlider, SIGNAL(valueChanged(int)), glWidget, SLOT(setYRotation(int)));
connect(glWidget, SIGNAL(yRotationChanged(int)), ySlider, SLOT(setValue(int)));
connect(zSlider, SIGNAL(valueChanged(int)), glWidget, SLOT(setZRotation(int)));
connect(glWidget, SIGNAL(zRotationChanged(int)), zSlider, SLOT(setValue(int)));
QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->addWidget(glWidget);
mainLayout->addWidget(xSlider);
mainLayout->addWidget(ySlider);
mainLayout->addWidget(zSlider);
setLayout(mainLayout);
xSlider->setValue(15 * 16);
ySlider->setValue(345 * 16);
zSlider->setValue(0 * 16);
setWindowTitle(tr("Hello GL"));
}
QSlider *Window::createSlider()
{
QSlider *slider = new QSlider(Qt::Vertical);
slider->setRange(0, 360 * 16);
slider->setSingleStep(16);
slider->setPageStep(15 * 16);
slider->setTickInterval(15 * 16);
slider->setTickPosition(QSlider::TicksRight);
return slider;
}
|
#include <iostream>
#include <vector>
#include <initializer_list>
#include <utility>
#include <stdexcept>
#include <list>
template<class KeyType, class ValueType, class Hash = std::hash<KeyType>>
class HashMap {
private:
std::vector<std::vector<typename std::list<std::pair<const KeyType,
ValueType>>::iterator>> Data; // data[pos].size() == 2 means marked position -- elem was deleted. When next relocate will happen, this node will be deleted from data
std::list<std::pair<const KeyType, ValueType>> all_elems;
Hash my_H;
size_t count_el;
size_t cap;
public:
HashMap(const Hash& a = Hash()) : my_H(a), count_el(0) {
Data.resize(2);
cap = 2;
}
template<typename It>
HashMap(It start, It end, const Hash& a = Hash()) : my_H(a), count_el(0) {
Data.resize(2);
cap = 2;
while (start != end) {
insert(*start);
}
}
HashMap(const std::initializer_list<std::pair<KeyType, ValueType>>& arr,
const Hash& a = Hash()) : my_H(a), count_el(0) {
cap = 2;
Data.resize(2);
for (const auto& i : arr) {
insert(i);
}
}
void relocate() { // do relocation when the table is too big or too small compared to count_el
if (count_el >= cap / 4 && count_el < cap / 2) {
return;
}
size_t new_size = 0;
if (count_el < cap / 4) {
new_size = cap / 2;
} else if (count_el >= cap / 2) {
new_size = cap * 2;
}
if (new_size == 0) {
return;
}
cap = new_size;
for (int i = 0; i < Data.size(); ++i) {
Data[i].clear();
}
Data.clear();
Data.resize(new_size);
for (auto i = all_elems.begin(); i != all_elems.end(); ++i) {
size_t id = my_H((*i).first) % cap;
while (Data[id].size() != 0) {
++id;
id %= cap;
}
Data[id].push_back(i);
}
}
size_t size() const {
return count_el;
}
bool empty() const {
return count_el == 0;
}
Hash hash_function() const {
return my_H;
}
void insert(const std::pair<const KeyType, ValueType>& elem) {
size_t id = my_H(elem.first) % cap;
while (Data[id].size() == 1) {
if ((*(*Data[id].begin())).first == elem.first) {
break;
}
id += 1;
id %= cap;
}
if (Data[id].size() == 0) {
all_elems.push_back(elem);
auto it = all_elems.end();
--it;
Data[id].push_back(it);
++count_el;
relocate();
} else if (Data[id].size() == 2) {
all_elems.push_back(elem);
auto it = all_elems.end();
--it;
Data[id].clear();
Data[id].push_back(it);
++count_el;
relocate();
}
}
void erase(const KeyType& key) {
size_t id = my_H(key) % cap;
size_t pos = 0;
while (Data[id].size() != 0) {
if (Data[id].size() != 2 && (*Data[id][0]).first == key) {
break;
}
++id;
id %= cap;
}
if (Data[id].size() != 0) {
--count_el;
all_elems.erase(Data[id][0]);
Data[id].push_back(Data[id][0]);
relocate();
}
}
typedef typename std::list<std::pair<const KeyType, ValueType>>::iterator iterator;
typedef typename std::list<std::pair<const KeyType, ValueType>>::const_iterator const_iterator;
iterator begin() {
return all_elems.begin();
}
iterator end() {
return all_elems.end();
}
const_iterator begin() const {
return all_elems.cbegin();
}
const_iterator end() const {
return all_elems.cend();
}
iterator find(const KeyType& key) {
size_t id = my_H(key) % cap;
size_t pos = 0;
while (Data[id].size() != 0) {
if (Data[id].size() != 2 && (*Data[id][0]).first == key) {
break;
}
++id;
id %= cap;
}
if (Data[id].size() == 0) {
return end();
}
return (*Data[id].begin());
}
const_iterator find(const KeyType& key) const {
size_t id = my_H(key) % cap;
size_t pos = 0;
while (Data[id].size() != 0) {
if (Data[id].size() != 2 && (*Data[id][0]).first == key) {
break;
}
++id;
id %= cap;
}
if (Data[id].size() == 0) {
return end();
}
return (*Data[id].begin());
}
ValueType& operator[](const KeyType& key) {
size_t id = my_H(key) % cap;
while (Data[id].size() != 0) {
if (Data[id].size() != 2 && (*Data[id][0]).first == key) {
break;
}
++id;
id %= cap;
}
if (Data[id].size() == 0) {
insert(std::make_pair(key, ValueType()));
return (*find(key)).second;
}
return (*(Data[id][0])).second;
}
const ValueType& at(const KeyType& key) const {
size_t id = my_H(key) % cap;
while (Data[id].size() != 0) {
if (Data[id].size() != 2 && (*Data[id][0]).first == key) {
break;
}
++id;
id %= cap;
}
if (Data[id].size() == 0) {
throw std::out_of_range("Out Of Range");
}
return (*(Data[id][0])).second;
}
void clear() {
Data.clear();
Data.resize(2);
cap = 2;
count_el = 0;
all_elems.clear();
}
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* THIS FILE IS AUTOMATICALLY GENERATED - DO NOT EDIT!
*
*/
#include "core/pch_system_includes.h"
#ifdef VEGA_BACKEND_OPENGL
#define VEGA_OPENGL_SHADERDATA_DEFINED
const char* g_GLSL_ShaderData[] = {
// SHADER_VECTOR2D
"uniform sampler2D src;\n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"void main() {\n"
" gl_FragColor = texture2D_wrap(src, vTexCoord0) * vert_color;\n"
"}\n",
// SHADER_VECTOR2DTEXGEN
"uniform sampler2D src;\n"
"uniform sampler2D stencilSrc;\n"
"uniform sampler2D maskSrc;\n"
"uniform bool stencilComponentBased;\n"
"uniform bool straightAlpha;\n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord2;\n"
"varying vec2 vTexCoord3;\n"
"const vec3 lumfactors = vec3(0.2125, 0.7154, 0.0721);\n"
"void main() {\n"
" vec4 stencil = texture2D(stencilSrc, vTexCoord2);\n"
" if (stencilComponentBased)\n"
" {\n"
" float lum = dot(stencil.rgb, lumfactors);\n"
" stencil = vec4(lum);\n"
" }\n"
" float maskAlpha = texture2D(maskSrc, vTexCoord3).a;\n"
" float maskColor = max(float(straightAlpha), maskAlpha);\n"
" vec4 mask = vec4(maskColor, maskColor, maskColor, maskAlpha);\n"
" gl_FragColor = texture2D_wrap(src, vTexCoord0) * stencil * mask * vert_color;\n"
"}\n",
// SHADER_VECTOR2DTEXGENRADIAL
"uniform sampler2D src;\n"
"uniform sampler2D stencilSrc;\n"
"uniform sampler2D maskSrc;\n"
"uniform bool stencilComponentBased;\n"
"uniform bool straightAlpha;\n"
"uniform float uSrcY;\n"
"uniform vec3 uFocusPoint; \n"
"uniform vec3 uCenterPoint; \n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord2;\n"
"varying vec2 vTexCoord3;\n"
"const vec3 lumfactors = vec3(0.2125, 0.7154, 0.0721);\n"
"void main() {\n"
" vec3 cd = uCenterPoint - uFocusPoint;\n"
" vec3 pd;\n"
" pd.xy = vTexCoord0 - uFocusPoint.xy;\n"
" pd.z = uFocusPoint.z;\n"
" float a = dot(cd.xy, cd.xy) - cd.z*cd.z; \n"
" float b = dot(pd, cd);\n"
" float c = dot(pd.xy, pd.xy) - pd.z*pd.z;\n"
" float offset;\n"
" float scale = texture2D(maskSrc, vTexCoord3).a;\n"
" if (abs(a) < 0.001)\n"
" {\n"
" offset = c / (2.0 * b);\n"
" scale *= step(0.001, abs(b));\n"
" }\n"
" else\n"
" {\n"
" float bbac = b*b-a*c;\n"
" scale *= step(0.0, bbac);\n"
" bbac = sqrt(bbac) / a;\n"
" b /= a;\n"
" offset = b + bbac;\n"
" offset -= step(offset*cd.z, -uFocusPoint.z)*2.0*bbac;\n"
" }\n"
" scale *= step(-uFocusPoint.z, offset*cd.z);\n"
" vec4 stencil = texture2D(stencilSrc, vTexCoord2);\n"
" if (stencilComponentBased)\n"
" {\n"
" float lum = dot(stencil.rgb, lumfactors);\n"
" stencil = vec4(lum);\n"
" }\n"
" float maskColor = max(float(straightAlpha), scale);\n"
" vec4 mask = vec4(maskColor, maskColor, maskColor, scale);\n"
" vec4 col = texture2D(src, vec2(offset, uSrcY)) * stencil * mask * vert_color;\n"
" gl_FragColor = col;\n"
"}\n",
// SHADER_VECTOR2DTEXGENRADIALSIMPLE
"#ifdef GL_ES\n"
"precision mediump float;\n"
"#endif\n"
"uniform sampler2D src;\n"
"uniform sampler2D stencilSrc;\n"
"uniform sampler2D maskSrc;\n"
"uniform bool stencilComponentBased;\n"
"uniform bool straightAlpha;\n"
"uniform float uSrcY;\n"
"uniform vec3 uFocusPoint; \n"
"uniform vec3 uCenterPoint; \n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord2;\n"
"varying vec2 vTexCoord3;\n"
"const vec3 lumfactors = vec3(0.2125, 0.7154, 0.0721);\n"
"void main() {\n"
" vec2 cd = uCenterPoint.xy - uFocusPoint.xy;\n"
" vec2 pd = vTexCoord0 - uFocusPoint.xy;\n"
" float offset;\n"
" float scale = texture2D(maskSrc, vTexCoord3).a;\n"
" scale *= uFocusPoint.z < 0.001 ? 1.0 : 0.0;\n"
" float rr = uCenterPoint.z*uCenterPoint.z;\n"
" float pdp = dot(pd.xy, pd.xy);\n"
" if (all(equal(uFocusPoint.xy, uCenterPoint.xy)))\n"
" {\n"
" offset = sqrt(pdp/rr);\n"
" }\n"
" else\n"
" {\n"
" float ppc = pd.x*cd.y - pd.y*cd.x;\n"
" float pdc = dot(pd.xy, cd.xy);\n"
" offset = pdp / (pdc + sqrt(rr * pdp - ppc*ppc));\n"
" }\n"
" vec4 stencil = texture2D(stencilSrc, vTexCoord2);\n"
" if (stencilComponentBased)\n"
" {\n"
" float lum = dot(stencil.rgb, lumfactors);\n"
" stencil = vec4(lum);\n"
" }\n"
" float maskColor = max(float(straightAlpha), scale);\n"
" vec4 mask = vec4(maskColor, maskColor, maskColor, scale);\n"
" vec4 col = texture2D(src, vec2(offset, uSrcY)) * stencil * mask * vert_color;\n"
" gl_FragColor = col;\n"
"}\n",
// SHADER_TEXT2D
"uniform sampler2D src;\n"
"uniform vec4 alphaComponent;\n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"void main() {\n"
" float alpha = dot(texture2D(src, vTexCoord0), alphaComponent);\n"
" gl_FragColor = vert_color * alpha;\n"
"}\n",
// SHADER_TEXT2DTEXGEN
"uniform sampler2D src;\n"
"uniform sampler2D stencilSrc;\n"
"uniform vec4 alphaComponent;\n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord2;\n"
"void main() {\n"
" float alpha = dot(texture2D(src, vTexCoord0), alphaComponent);\n"
" gl_FragColor = vert_color * alpha * texture2D(stencilSrc, vTexCoord2);\n"
"}\n",
// SHADER_TEXT2DEXTBLEND
"#version 130\n"
"uniform sampler2D src;\n"
"in vec4 vert_color;\n"
"out vec4 fragColor0;\n"
"out vec4 fragColor1;\n"
"varying vec2 vTexCoord0;\n"
"void main() {\n"
" vec4 subpixel_alpha = texture2D(src, vTexCoord0);\n"
" fragColor0 = vert_color * subpixel_alpha;\n"
" fragColor1 = subpixel_alpha * vert_color.a;\n"
"}\n",
// SHADER_TEXT2DEXTBLENDTEXGEN
"#version 130\n"
"uniform sampler2D src;\n"
"uniform sampler2D stencilSrc;\n"
"in vec4 vert_color;\n"
"out vec4 fragColor0;\n"
"out vec4 fragColor1;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord2;\n"
"void main() {\n"
" vec4 subpixel_alpha = texture2D(src, vTexCoord0) * texture2D(stencilSrc, vTexCoord2);\n"
" fragColor0 = vert_color * subpixel_alpha;\n"
" fragColor1 = subpixel_alpha * vert_color.a;\n"
"}\n",
// SHADER_TEXT2D_INTERPOLATE
"uniform sampler2D src;\n"
"uniform sampler2D src2;\n"
"uniform vec4 alphaComponent;\n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"void main() {\n"
" float intensity = dot(vert_color.rgb, vec3(0.2125, 0.7154, 0.0721))/vert_color.a;\n"
" float alpha = dot(mix(texture2D(src, vTexCoord0), texture2D(src2, vTexCoord0), intensity), alphaComponent);\n"
" gl_FragColor = vert_color * alpha;\n"
"}\n",
// SHADER_TEXT2DTEXGEN_INTERPOLATE
"uniform sampler2D src;\n"
"uniform sampler2D src2;\n"
"uniform sampler2D stencilSrc;\n"
"uniform vec4 alphaComponent;\n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord2;\n"
"void main() {\n"
" float intensity = dot(vert_color.rgb, vec3(0.2125, 0.7154, 0.0721))/vert_color.a;\n"
" float alpha = dot(mix(texture2D(src, vTexCoord0), texture2D(src2, vTexCoord0), intensity), alphaComponent);\n"
" gl_FragColor = vert_color * alpha * texture2D(stencilSrc, vTexCoord2);\n"
"}\n",
// SHADER_TEXT2DEXTBLEND_INTERPOLATE
"#version 130\n"
"uniform sampler2D src;\n"
"uniform sampler2D src2;\n"
"in vec4 vert_color;\n"
"out vec4 fragColor0;\n"
"out vec4 fragColor1;\n"
"varying vec2 vTexCoord0;\n"
"void main() {\n"
" float intensity = dot(vert_color.rgb, vec3(0.2125, 0.7154, 0.0721))/vert_color.a;\n"
" vec4 subpixel_alpha = mix(texture2D(src, vTexCoord0), texture2D(src2, vTexCoord0), intensity);\n"
" fragColor0 = vert_color * subpixel_alpha;\n"
" fragColor1 = subpixel_alpha * vert_color.a;\n"
"}\n",
// SHADER_TEXT2DEXTBLENDTEXGEN_INTERPOLATE
"#version 130\n"
"uniform sampler2D src;\n"
"uniform sampler2D src2;\n"
"uniform sampler2D stencilSrc;\n"
"in vec4 vert_color;\n"
"out vec4 fragColor0;\n"
"out vec4 fragColor1;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord2;\n"
"void main() {\n"
" float intensity = dot(vert_color.rgb, vec3(0.2125, 0.7154, 0.0721))/vert_color.a;\n"
" vec4 subpixel_alpha = mix(texture2D(src, vTexCoord0), texture2D(src2, vTexCoord0), intensity) * texture2D(stencilSrc, vTexCoord2);\n"
" fragColor0 = vert_color * subpixel_alpha;\n"
" fragColor1 = subpixel_alpha * vert_color.a;\n"
"}\n",
// SHADER_COLORMATRIX
"uniform sampler2D src;\n"
"uniform mat4 colormat;\n"
"uniform vec4 colorbias;\n"
"varying vec2 vTexCoord0;\n"
"vec4 unpremultiply(vec4 v)\n"
"{\n"
" return v.a <= 0.0 ? v : vec4(v.rgb / v.a, v.a);\n"
"}\n"
"vec4 premultiply(vec4 v)\n"
"{\n"
" float a = clamp(v.a, 0.0, 1.0);\n"
" return vec4(v.rgb * a, a);\n"
"}\n"
"void main() {\n"
" vec4 s = unpremultiply(texture2D(src, vTexCoord0));\n"
" s = premultiply(s * colormat + colorbias);\n"
" gl_FragColor = clamp(s, 0.0, 1.0);\n"
"}\n",
// SHADER_COMPONENTTRANSFER
"uniform sampler2D src;\n"
"uniform sampler2D map;\n"
"varying vec2 vTexCoord0;\n"
"vec4 unpremultiply(vec4 v)\n"
"{\n"
" return v.a <= 0.0 ? v : vec4(v.rgb / v.a, v.a);\n"
"}\n"
"vec4 premultiply(vec4 v)\n"
"{\n"
" return vec4(v.rgb * v.a, v.a);\n"
"}\n"
"void main()\n"
"{\n"
" vec4 c = unpremultiply(texture2D(src, vTexCoord0));\n"
" c.r = texture2D(map, vec2(c.r, 0.0)).a;\n"
" c.g = texture2D(map, vec2(c.g, 0.25)).a;\n"
" c.b = texture2D(map, vec2(c.b, 0.5)).a;\n"
" c.a = texture2D(map, vec2(c.a, 0.75)).a;\n"
" gl_FragColor = premultiply(c);\n"
"}\n",
// SHADER_DISPLACEMENT
"uniform sampler2D src;\n"
"uniform sampler2D displace_map;\n"
"uniform vec4 xselector;\n"
"uniform vec4 yselector;\n"
"uniform vec2 src_scale;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord1;\n"
"float clampStep(vec2 texpos)\n"
"{\n"
"\treturn step(0, texpos.s) * step(texpos.s, 1) * step(0, texpos.t) * step(texpos.t, 1);\n"
"}\n"
"void main()\n"
"{\n"
" vec4 d = texture2D(displace_map, vTexCoord1);\n"
" vec2 offset = vec2(dot(xselector, d), dot(yselector, d));\n"
" offset = (offset - vec2(0.5, 0.5)) * src_scale;\n"
" vec2 texpos = vTexCoord0 + offset;\n"
" gl_FragColor = texture2D(src, texpos) * clampStep(texpos);\n"
"}\n",
// SHADER_LUMINANCE_TO_ALPHA
"uniform sampler2D src;\n"
"varying vec2 vTexCoord0;\n"
"const vec3 lumfactors = vec3(0.2125, 0.7154, 0.0721);\n"
"vec4 unpremultiply(vec4 v)\n"
"{\n"
" return v.a <= 0.0 ? v : vec4(v.rgb / v.a, v.a);\n"
"}\n"
"void main()\n"
"{\n"
" vec4 s = unpremultiply(texture2D(src, vTexCoord0));\n"
" gl_FragColor = vec4(0.0, 0.0, 0.0, dot(s.rgb, lumfactors));\n"
"}\n",
// SHADER_SRGB_TO_LINEARRGB
"uniform sampler2D src;\n"
"const vec3 gamma = vec3(2.4, 2.4, 2.4);\n"
"const vec3 offset = vec3(0.055, 0.055, 0.055);\n"
"varying vec2 vTexCoord0;\n"
"vec4 unpremultiply(vec4 v)\n"
"{\n"
" return v.a <= 0.0 ? v : vec4(v.rgb / v.a, v.a);\n"
"}\n"
"void main()\n"
"{\n"
" vec4 s = unpremultiply(texture2D(src, vTexCoord0));\n"
" vec3 c = pow((s.rgb + offset) / 1.055, gamma);\n"
" gl_FragColor = vec4(c * s.a, s.a);\n"
"}\n",
// SHADER_LINEARRGB_TO_SRGB
"uniform sampler2D src;\n"
"varying vec2 vTexCoord0;\n"
"const vec3 invgamma = vec3(1.0/2.4, 1.0/2.4, 1.0/2.4);\n"
"const vec3 offset = vec3(0.055, 0.055, 0.055);\n"
"vec4 unpremultiply(vec4 v)\n"
"{\n"
" return v.a <= 0.0 ? v : vec4(v.rgb / v.a, v.a);\n"
"}\n"
"void main()\n"
"{\n"
" vec4 s = unpremultiply(texture2D(src, vTexCoord0));\n"
" vec3 c = 1.055 * pow(s.rgb, invgamma) - offset;\n"
" gl_FragColor = vec4(c * s.a, s.a);\n"
"}\n",
// SHADER_MERGE_ARITHMETIC
"uniform sampler2D src1;\n"
"uniform sampler2D src2;\n"
"uniform float k1;\n"
"uniform float k2;\n"
"uniform float k3;\n"
"uniform float k4;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord1;\n"
"void main()\n"
"{\n"
" vec4 i1 = texture2D(src1, vTexCoord0);\n"
" vec4 i2 = texture2D(src2, vTexCoord1);\n"
" vec4 result = k1 * i1 * i2 + k2 * i1 + k3 * i2 + k4;\n"
" gl_FragColor = clamp(result, 0.0, 1.0);\n"
"}\n",
// SHADER_MERGE_MULTIPLY
"uniform sampler2D src1;\n"
"uniform sampler2D src2;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord1;\n"
"void main()\n"
"{\n"
" vec4 i1 = texture2D(src1, vTexCoord0);\n"
" vec4 i2 = texture2D(src2, vTexCoord1);\n"
" float qr = 1.0 - (1.0 - i1.a) * (1.0 - i2.a);\n"
" vec3 cr = (1.0 - i1.a) * i2.rgb + (1.0 - i2.a) * i1.rgb + i1.rgb * i2.rgb;\n"
" gl_FragColor = vec4(clamp(cr, 0.0, 1.0), qr);\n"
"}\n",
// SHADER_MERGE_SCREEN
"uniform sampler2D src1;\n"
"uniform sampler2D src2;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord1;\n"
"void main()\n"
"{\n"
" vec4 i1 = texture2D(src1, vTexCoord0);\n"
" vec4 i2 = texture2D(src2, vTexCoord1);\n"
" vec4 result = i2 + i1 - i1 * i2;\n"
" gl_FragColor = clamp(result, 0.0, 1.0);\n"
"}\n",
// SHADER_MERGE_DARKEN
"uniform sampler2D src1;\n"
"uniform sampler2D src2;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord1;\n"
"void main()\n"
"{\n"
" vec4 i1 = texture2D(src1, vTexCoord0);\n"
" vec4 i2 = texture2D(src2, vTexCoord1);\n"
" float qr = 1.0 - (1.0 - i1.a) * (1.0 - i2.a);\n"
" vec3 cr = min((1.0 - i1.a) * i2.rgb + i1.rgb, (1.0 - i2.a) * i1.rgb + i2.rgb);\n"
" gl_FragColor = vec4(cr, qr);\n"
"}\n",
// SHADER_MERGE_LIGHTEN
"uniform sampler2D src1;\n"
"uniform sampler2D src2;\n"
"varying vec2 vTexCoord0;\n"
"varying vec2 vTexCoord1;\n"
"void main()\n"
"{\n"
" vec4 i1 = texture2D(src1, vTexCoord0);\n"
" vec4 i2 = texture2D(src2, vTexCoord1);\n"
" float qr = 1.0 - (1.0 - i1.a) * (1.0 - i2.a);\n"
" vec3 cr = max((1.0 - i1.a) * i2.rgb + i1.rgb, (1.0 - i2.a) * i1.rgb + i2.rgb);\n"
" gl_FragColor = vec4(cr, qr);\n"
"}\n",
// SHADER_LIGHTING_DISTANTLIGHT
"uniform sampler2D src;\n"
"uniform vec3 light_color;\n"
"uniform vec3 light_position;\n"
"uniform float light_kd;\n"
"uniform float light_ks;\n"
"uniform float light_specexp;\n"
"uniform float surface_scale;\n"
"uniform float k1;\n"
"uniform float k2;\n"
"uniform float k3;\n"
"uniform float k4;\n"
"uniform vec2 pixel_size; \n"
"varying vec2 vTexCoord0;\n"
"const vec3 eye_vec = vec3(0.0, 0.0, 1.0);\n"
"vec3 calc_surface_normal()\n"
"{\n"
" vec2 tc = vTexCoord0 + pixel_size * vec2(-1.0, -1.0);\n"
" vec2 co = pixel_size * vec2(1.0, 0.0); \n"
" vec2 ro = pixel_size * vec2(-2.0, 1.0); \n"
" float c00 = texture2D(src, tc).a; tc += co;\n"
" float c01 = texture2D(src, tc).a; tc += co;\n"
" float c02 = texture2D(src, tc).a; tc += ro;\n"
" float c10 = texture2D(src, tc).a; tc += co;\n"
" tc += co;\n"
" float c12 = texture2D(src, tc).a; tc += ro;\n"
" float c20 = texture2D(src, tc).a; tc += co;\n"
" float c21 = texture2D(src, tc).a; tc += co;\n"
" float c22 = texture2D(src, tc).a;\n"
" return normalize(vec3(-surface_scale * ((c02 + 2.0 * c12 + c22) - (c00 + 2.0 * c10 + c20)) / 4.0,\n"
" -surface_scale * ((c20 + 2.0 * c21 + c22) - (c00 + 2.0 * c01 + c02)) / 4.0,\n"
" 1.0));\n"
"}\n"
"void main()\n"
"{\n"
" vec3 n = calc_surface_normal();\n"
" float n_dot_h = max(dot(n, normalize(light_position + eye_vec)), 0.0);\n"
" float n_dot_l = max(dot(n, light_position), 0.0);\n"
" vec3 specular_color = clamp(light_color * light_ks * pow(n_dot_h, light_specexp), 0.0, 1.0);\n"
" vec3 diffuse_color = clamp(light_color * light_kd * n_dot_l, 0.0, 1.0);\n"
" float alpha = max(specular_color.r, max(specular_color.g, specular_color.b));\n"
" vec4 specular = vec4(specular_color * alpha, alpha);\n"
" vec4 diffuse = vec4(diffuse_color, 1.0);\n"
" vec4 combined = k1 * diffuse * specular + k2 * diffuse + k3 * specular + k4;\n"
" gl_FragColor = clamp(combined, 0.0, 1.0);\n"
"}\n",
// SHADER_LIGHTING_POINTLIGHT
"uniform sampler2D src;\n"
"uniform vec3 light_color;\n"
"uniform vec3 light_position;\n"
"uniform float light_kd;\n"
"uniform float light_ks;\n"
"uniform float light_specexp;\n"
"uniform float surface_scale;\n"
"uniform float k1;\n"
"uniform float k2;\n"
"uniform float k3;\n"
"uniform float k4;\n"
"uniform vec2 pixel_size; \n"
"varying vec2 vTexCoord0;\n"
"const vec3 eye_vec = vec3(0.0, 0.0, 1.0);\n"
"vec3 calc_surface_normal()\n"
"{\n"
" vec2 tc = vTexCoord0 + pixel_size * vec2(-1.0, -1.0);\n"
" vec2 co = pixel_size * vec2(1.0, 0.0); \n"
" vec2 ro = pixel_size * vec2(-2.0, 1.0); \n"
" float c00 = texture2D(src, tc).a; tc += co;\n"
" float c01 = texture2D(src, tc).a; tc += co;\n"
" float c02 = texture2D(src, tc).a; tc += ro;\n"
" float c10 = texture2D(src, tc).a; tc += co;\n"
" tc += co;\n"
" float c12 = texture2D(src, tc).a; tc += ro;\n"
" float c20 = texture2D(src, tc).a; tc += co;\n"
" float c21 = texture2D(src, tc).a; tc += co;\n"
" float c22 = texture2D(src, tc).a;\n"
" return normalize(vec3(-surface_scale * ((c02 + 2.0 * c12 + c22) - (c00 + 2.0 * c10 + c20)) / 4.0,\n"
" -surface_scale * ((c20 + 2.0 * c21 + c22) - (c00 + 2.0 * c01 + c02)) / 4.0,\n"
" 1.0));\n"
"}\n"
"void main()\n"
"{\n"
" float surf_height = texture2D(src, vTexCoord0).a * surface_scale;\n"
" vec3 surf_pos = vec3(vTexCoord0 / pixel_size, surf_height);\n"
" vec3 n = calc_surface_normal();\n"
" vec3 l = normalize(light_position - surf_pos);\n"
" float n_dot_l = max(dot(n, l), 0.0);\n"
" float n_dot_h = max(dot(n, normalize(l + eye_vec)), 0.0);\n"
" vec3 diffuse_color = clamp(light_color * light_kd * n_dot_l, 0.0, 1.0);\n"
" vec4 diffuse = vec4(diffuse_color, 1.0);\n"
" vec3 specular_color = clamp(light_color * light_ks * pow(n_dot_h, light_specexp), 0.0, 1.0);\n"
" float alpha = max(specular_color.r, max(specular_color.g, specular_color.b));\n"
" vec4 specular = vec4(specular_color * alpha, alpha);\n"
" vec4 combined = k1 * diffuse * specular + k2 * diffuse + k3 * specular + k4;\n"
" gl_FragColor = clamp(combined, 0.0, 1.0);\n"
"}\n",
// SHADER_LIGHTING_SPOTLIGHT
"uniform sampler2D src;\n"
"uniform vec3 light_color;\n"
"uniform vec3 light_position;\n"
"uniform float light_ks;\n"
"uniform float light_kd;\n"
"uniform float light_specexp;\n"
"uniform vec3 spot_dir;\n"
"uniform float spot_falloff;\n"
"uniform float spot_coneangle;\n"
"uniform float spot_specexp;\n"
"uniform bool spot_has_cone;\n"
"uniform float surface_scale;\n"
"uniform float k1;\n"
"uniform float k2;\n"
"uniform float k3;\n"
"uniform float k4;\n"
"uniform vec2 pixel_size; \n"
"varying vec2 vTexCoord0;\n"
"const vec3 eye_vec = vec3(0.0, 0.0, 1.0);\n"
"void main()\n"
"{\n"
" vec3 surf = (texture2D(src, vTexCoord0).xyz - vec3(0.5, 0.5, 0.0)) * surface_scale;\n"
" vec3 surf_pos = vec3(vTexCoord0 / pixel_size, surf.z);\n"
" vec3 n = normalize(vec3(-surf.xy, 1.0));\n"
" vec3 l = normalize(light_position - surf_pos);\n"
" float n_dot_l = max(dot(n, l), 0.0);\n"
" float n_dot_h = max(dot(n, normalize(l + eye_vec)), 0.0);\n"
" float l_dot_s = max(-dot(l, normalize(spot_dir)), 0.0);\n"
" float spot_att = pow(l_dot_s, spot_specexp);\n"
" if (spot_has_cone)\n"
" spot_att = clamp(spot_att * (l_dot_s - spot_falloff) / (spot_coneangle - spot_falloff), 0.0, 1.0);\n"
" vec3 diffuse_color = light_color * spot_att * clamp(light_kd * n_dot_l, 0.0, 1.0);\n"
" vec4 diffuse = vec4(diffuse_color, 1.0);\n"
" vec3 specular_color = light_color * spot_att * clamp(light_ks * pow(n_dot_h, light_specexp), 0.0, 1.0);\n"
" float alpha = max(specular_color.r, max(specular_color.g, specular_color.b));\n"
" vec4 specular = vec4(specular_color * alpha, alpha);\n"
" vec4 combined = k1 * diffuse * specular + k2 * diffuse + k3 * specular + k4;\n"
" gl_FragColor = clamp(combined, 0.0, 1.0);\n"
"}\n",
// SHADER_LIGHTING_MAKE_BUMP
"uniform sampler2D src;\n"
"uniform vec2 pixel_size; \n"
"varying vec2 vTexCoord0;\n"
"void main()\n"
"{\n"
" vec2 tc = vTexCoord0 - pixel_size;\n"
" vec2 co = pixel_size * vec2(1.0, 0.0); \n"
" vec2 ro = pixel_size * vec2(-2.0, 1.0); \n"
" float c00 = texture2D(src, tc).a; tc += co;\n"
" float c01 = texture2D(src, tc).a; tc += co;\n"
" float c02 = texture2D(src, tc).a; tc += ro;\n"
" float c10 = texture2D(src, tc).a; tc += co;\n"
" tc += co;\n"
" float c12 = texture2D(src, tc).a; tc += ro;\n"
" float c20 = texture2D(src, tc).a; tc += co;\n"
" float c21 = texture2D(src, tc).a; tc += co;\n"
" float c22 = texture2D(src, tc).a;\n"
" gl_FragColor = vec4(((c02 + 2.0 * c12 + c22) - (c00 + 2.0 * c10 + c20)) / 8.0 + 0.5,\n"
" ((c20 + 2.0 * c21 + c22) - (c00 + 2.0 * c01 + c02)) / 8.0 + 0.5,\n"
" texture2D(src, vTexCoord0).a,\n"
" 0.0);\n"
"}\n",
// SHADER_CONVOLVE_GEN_16
"uniform sampler2D src;\n"
"uniform vec4 coeffs[16]; \n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"void main()\n"
"{\n"
" vec4 sum = vec4(0.0, 0.0, 0.0, 0.0);\n"
" for (int i = 0; i < 16; ++i)\n"
" {\n"
" sum += texture2D_wrap(src, vTexCoord0 + coeffs[i].st) * coeffs[i].p;\n"
" }\n"
" gl_FragColor = sum*vert_color;\n"
"}\n",
// SHADER_CONVOLVE_GEN_16_BIAS
"uniform sampler2D src;\n"
"uniform vec4 coeffs[16]; \n"
"uniform float divisor;\n"
"uniform float bias;\n"
"uniform bool preserve_alpha;\n"
"varying vec2 vTexCoord0;\n"
"vec4 unpremultiply(vec4 v)\n"
"{\n"
" return v.a <= 0.0 ? v : vec4(v.rgb / v.a, v.a);\n"
"}\n"
"void main()\n"
"{\n"
" vec4 sum = vec4(0.0, 0.0, 0.0, 0.0);\n"
" for (int i = 0; i < 16; ++i)\n"
" {\n"
" sum += texture2D_wrap(src, vTexCoord0 + coeffs[i].st) * coeffs[i].p;\n"
" }\n"
" vec4 result = sum / divisor + bias;\n"
" if (preserve_alpha)\n"
" {\n"
" vec4 orig = texture2D_wrap(src, vTexCoord0);\n"
" result = unpremultiply(result);\n"
" result = vec4(result.rgb * orig.a, orig.a);\n"
" }\n"
" gl_FragColor = clamp(result, 0.0, 1.0);\n"
"}\n",
// SHADER_CONVOLVE_GEN_25_BIAS
"uniform sampler2D src;\n"
"uniform vec4 coeffs[25]; \n"
"uniform float divisor;\n"
"uniform float bias;\n"
"uniform bool preserve_alpha;\n"
"varying vec2 vTexCoord0;\n"
"vec4 unpremultiply(vec4 v)\n"
"{\n"
" return v.a <= 0.0 ? v : vec4(v.rgb / v.a, v.a);\n"
"}\n"
"void main()\n"
"{\n"
" vec4 sum = vec4(0.0, 0.0, 0.0, 0.0);\n"
" for (int i = 0; i < 25; ++i)\n"
" {\n"
" sum += texture2D_wrap(src, vTexCoord0 + coeffs[i].st) * coeffs[i].p;\n"
" }\n"
" vec4 result = sum / divisor + bias;\n"
" if (preserve_alpha)\n"
" {\n"
" vec4 orig = texture2D_wrap(src, vTexCoord0);\n"
" result = unpremultiply(result);\n"
" result = vec4(result.rgb * orig.a, orig.a);\n"
" }\n"
" gl_FragColor = clamp(result, 0.0, 1.0);\n"
"}\n",
// SHADER_MORPHOLOGY_DILATE_15
"uniform sampler2D src;\n"
"uniform vec4 offsets[7];\n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"void main()\n"
"{\n"
" vec4 t = texture2D_wrap(src, vTexCoord0);\n"
" for (int i = 0; i < 7; ++i)\n"
" {\n"
" t = max(t, texture2D_wrap(src, vTexCoord0 + offsets[i].st));\n"
" t = max(t, texture2D_wrap(src, vTexCoord0 - offsets[i].st));\n"
" }\n"
" gl_FragColor = t*vert_color;\n"
"}\n",
// SHADER_MORPHOLOGY_ERODE_15
"uniform sampler2D src;\n"
"uniform vec4 offsets[7];\n"
"varying vec4 vert_color;\n"
"varying vec2 vTexCoord0;\n"
"void main()\n"
"{\n"
" vec4 t = texture2D_wrap(src, vTexCoord0);\n"
" for (int i = 0; i < 7; ++i)\n"
" {\n"
" t = min(t, texture2D_wrap(src, vTexCoord0 + offsets[i].st));\n"
" t = min(t, texture2D_wrap(src, vTexCoord0 - offsets[i].st));\n"
" }\n"
" gl_FragColor = t*vert_color;\n"
"}\n",
// SHADER_CUSTOM
NULL,
// vert2d.shd
"attribute vec4 inPosition;"
"attribute vec2 inTex;"
"attribute vec4 inColor;"
"attribute vec2 inTex2;"
"uniform mat4 worldProjMatrix;"
"uniform vec4 texTransS[2];"
"uniform vec4 texTransT[2];"
"varying vec4 vert_color;"
"varying vec2 vTexCoord0;"
"varying vec2 vTexCoord1;"
"varying vec2 vTexCoord2;"
"varying vec2 vTexCoord3;"
"void main() {"
" gl_Position = worldProjMatrix * inPosition;"
" vTexCoord0 = inTex;"
" vTexCoord1 = inTex2;"
" vTexCoord2.s = dot(texTransS[0], inPosition);"
" vTexCoord2.t = dot(texTransT[0], inPosition);"
" vTexCoord3.s = dot(texTransS[1], inPosition);"
" vTexCoord3.t = dot(texTransT[1], inPosition);"
" vert_color = inColor;"
"}"
};
#endif // VEGA_BACKEND_OPENGL
|
#include "GameObject.h"
#include "Sound.h"
#include "sdlwrap.h"
#include <SDL_render.h>
#include <string>
using std::vector;
Zombie::Zombie(int x, int y)
: _x(x), _y(y)
{
_hp = Zombie::defaultHp();
}
float Zombie::x() const { return _x; }
float Zombie::y() const { return _y; }
void Zombie::x(float x) { _x = x; }
void Zombie::y(float y) { _y = y; }
float Zombie::angle() const { return _angle; }
float Zombie::speed() const { return _speed; }
void Zombie::angle(float a) { _angle = a; }
void Zombie::speed(float s) { _speed = s; }
Circle Zombie::circle() const { return Circle(_x, _y, 25); }
int Zombie::hp() const { return _hp; }
int Zombie::defaultHp() const { return 50; }
int Zombie::dmg() const { if(_state == ATTACKING && _frame == 5) return 15; else return 0; }
std::string Zombie::texName() const {
std::string name = "zombie";
if(_state == ATTACKING) {
name += "_attack";
name += std::to_string(_frame);
}
else if(_state == DYING) {
name += "_death";
name += std::to_string(_frame);
}
return name;
}
void Zombie::damage(int d) {
if(d > 0) _hp -= d;
if(_hp <= 0 && _state != DYING) {
_state = DYING;
_frame = 0;
}
}
void Zombie::set_target(float x, float y, bool ignore) {
if(ignore || _state == DYING) return;
_angle = to_deg(get_angle(_x, _y, x, y));
auto dist = get_distance(_x, _y, x, y);
if(dist > circle().r * 1.7f) {
if(_state != MOVING) {
_state = MOVING;
_frame = 0;
}
}
else if(_state != ATTACKING) {
_state = ATTACKING;
_frame = 0;
}
}
void Zombie::handle_logic() {
if(_state == DYING) return;
if(_state == MOVING) {
default_move();
}
}
void Zombie::handle_render() {
default_render();
default_render_health(SDL_Color{0, 0x77, 0, 0xFF});
if(_state == ATTACKING) {
if(_frame == 5) {
sounds("zombie_attack").play();
}
if(_timer.passed(100)) {
++_frame;
if(_frame >= 6) _frame = 0;
_timer.start();
}
}
else if(_state == DYING) {
if(_frame < 7 && _timer.passed(500)) {
++_frame;
_timer.start();
}
}
}
bool Zombie::dead() const {
return _state == DYING && _frame == 7;
}
vector<Zombie>& zombies() {
static vector<Zombie> ret;
return ret;
}
|
#ifndef ITEM_H_
#define ITEM_H_
#include <string>
#include "Triggers.h"
#include "Status.h"
using namespace std;
class Item{
public:
Item();
string getName();
void setName(string);
Status getStatus();
void setStatus(Status);
string getWriting();
void setWriting(string);
string getOnFlag();
void setOnFlag(string);
string getDescription();
void setDescription(string);
Triggers * getTriggers();
void setTriggers(Triggers*);
void turn_on();
void turn_off();
private:
string name;
Status status;
string writing;
string description;
Triggers * triggers;
int on_off;
string onFlag;
};
#endif
|
/**
* Copyright (c) 2015, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LNAV_PLAIN_TEXT_SOURCE_HH
#define LNAV_PLAIN_TEXT_SOURCE_HH
#include <string>
#include <vector>
#include "base/attr_line.hh"
#include "base/file_range.hh"
#include "document.sections.hh"
#include "textview_curses.hh"
class plain_text_source
: public text_sub_source
, public vis_location_history
, public text_anchors {
public:
struct text_line {
text_line(file_off_t off, attr_line_t value)
: tl_offset(off), tl_value(std::move(value))
{
}
bool contains_offset(file_off_t off) const
{
return (this->tl_offset <= off
&& off < this->tl_offset + this->tl_value.length());
}
file_off_t tl_offset;
attr_line_t tl_value;
};
plain_text_source() = default;
plain_text_source(const std::string& text);
plain_text_source(const std::vector<std::string>& text_lines);
plain_text_source(const std::vector<attr_line_t>& text_lines);
plain_text_source& set_reverse_selection(bool val)
{
this->tds_reverse_selection = val;
return *this;
}
plain_text_source& replace_with(const attr_line_t& text_lines);
plain_text_source& replace_with(const std::vector<std::string>& text_lines);
void clear();
plain_text_source& truncate_to(size_t max_lines);
size_t text_line_count() override { return this->tds_lines.size(); }
bool empty() const { return this->tds_lines.empty(); }
size_t text_line_width(textview_curses& curses) override;
void text_value_for_line(textview_curses& tc,
int row,
std::string& value_out,
line_flags_t flags) override;
void text_attrs_for_line(textview_curses& tc,
int line,
string_attrs_t& value_out) override;
size_t text_size_for_line(textview_curses& tc,
int row,
line_flags_t flags) override;
text_format_t get_text_format() const override;
const std::vector<text_line>& get_lines() const { return this->tds_lines; }
plain_text_source& set_text_format(text_format_t format)
{
this->tds_text_format = format;
return *this;
}
nonstd::optional<location_history*> get_location_history() override
{
return this;
}
void text_crumbs_for_line(int line,
std::vector<breadcrumb::crumb>& crumbs) override;
nonstd::optional<vis_line_t> row_for_anchor(const std::string& id) override;
nonstd::optional<std::string> anchor_for_row(vis_line_t vl) override;
std::unordered_set<std::string> get_anchors() override;
protected:
size_t compute_longest_line();
nonstd::optional<vis_line_t> line_for_offset(file_off_t off) const;
std::vector<text_line> tds_lines;
text_format_t tds_text_format{text_format_t::TF_UNKNOWN};
size_t tds_longest_line{0};
bool tds_reverse_selection{false};
lnav::document::metadata tds_doc_sections;
};
#endif // LNAV_PLAIN_TEXT_SOURCE_HH
|
/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "internal/abstract-view-private.hpp"
#include "internal/abstract-event-handler-private.hpp"
namespace skland {
Task AbstractEventHandler::kRedrawTaskHead;
Task AbstractEventHandler::kRedrawTaskTail;
AbstractEventHandler::AbstractEventHandler()
: Trackable() {
p_.reset(new Private(this));
}
AbstractEventHandler::~AbstractEventHandler() {
}
void AbstractEventHandler::InitializeRedrawTaskList() {
kRedrawTaskHead.PushBack(&kRedrawTaskTail);
}
void AbstractEventHandler::ClearRedrawTaskList() {
Task *task = kRedrawTaskHead.next();
Task *next_task = nullptr;
while (task != &kRedrawTaskTail) {
next_task = task->next();
task->Unlink();
task = next_task;
}
}
void AbstractEventHandler::Damage(AbstractEventHandler *object, int surface_x, int surface_y, int width, int height) {
object->p_->is_damaged_ = true;
object->p_->damaged_region_.l = surface_x;
object->p_->damaged_region_.t = surface_y;
object->p_->damaged_region_.Resize(width, height);
}
}
|
// Copyright (c) 2017 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 _StdStorage_TypeData_HeaderFile
#define _StdStorage_TypeData_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StdStorage_MapOfTypes.hxx>
#include <Storage_Error.hxx>
#include <TCollection_AsciiString.hxx>
#include <Standard_Transient.hxx>
#include <Standard_Integer.hxx>
#include <StdObjMgt_MapOfInstantiators.hxx>
#include <TColStd_HSequenceOfAsciiString.hxx>
class Storage_BaseDriver;
class StdStorage_TypeData;
DEFINE_STANDARD_HANDLE(StdStorage_TypeData, Standard_Transient)
//! Storage type data section keeps association between
//! persistent textual types and their numbers
class StdStorage_TypeData
: public Standard_Transient
{
friend class StdStorage_Data;
public:
DEFINE_STANDARD_RTTIEXT(StdStorage_TypeData, Standard_Transient)
//! Reads the type data section from the container defined by theDriver.
//! Returns Standard_True in case of success. Otherwise, one need to get
//! an error code and description using ErrorStatus and ErrorStatusExtension
//! functions correspondingly.
Standard_EXPORT Standard_Boolean Read(const Handle(Storage_BaseDriver)& theDriver);
//! Writes the type data section to the container defined by theDriver.
//! Returns Standard_True in case of success. Otherwise, one need to get
//! an error code and description using ErrorStatus and ErrorStatusExtension
//! functions correspondingly.
Standard_EXPORT Standard_Boolean Write(const Handle(Storage_BaseDriver)& theDriver);
//! Returns the number of registered types
Standard_EXPORT Standard_Integer NumberOfTypes() const;
//! Add a type to the list in case of reading data
Standard_EXPORT void AddType (const TCollection_AsciiString& aTypeName, const Standard_Integer aTypeNum);
//! Add a type of the persistent object in case of writing data
Standard_EXPORT Standard_Integer AddType (const Handle(StdObjMgt_Persistent)& aPObj);
//! Returns the name of the type with number <aTypeNum>
Standard_EXPORT TCollection_AsciiString Type (const Standard_Integer aTypeNum) const;
//! Returns the name of the type with number <aTypeNum>
Standard_EXPORT Standard_Integer Type (const TCollection_AsciiString& aTypeName) const;
//! Returns a persistent object instantiator of <aTypeName>
Standard_EXPORT StdObjMgt_Persistent::Instantiator Instantiator(const Standard_Integer aTypeNum) const;
//! Checks if <aName> is a registered type
Standard_EXPORT Standard_Boolean IsType (const TCollection_AsciiString& aName) const;
//! Returns a sequence of all registered types
Standard_EXPORT Handle(TColStd_HSequenceOfAsciiString) Types() const;
//! Returns a status of the latest call to Read / Write functions
Standard_EXPORT Storage_Error ErrorStatus() const;
//! Returns an error message if any of the latest call to Read / Write functions
Standard_EXPORT TCollection_AsciiString ErrorStatusExtension() const;
//! Clears error status
Standard_EXPORT void ClearErrorStatus();
//! Unregisters all types
Standard_EXPORT void Clear();
private:
Standard_EXPORT StdStorage_TypeData();
Standard_EXPORT void SetErrorStatus (const Storage_Error anError);
Standard_EXPORT void SetErrorStatusExtension (const TCollection_AsciiString& anErrorExt);
Standard_Integer myTypeId;
StdObjMgt_MapOfInstantiators myMapOfPInst;
StdStorage_MapOfTypes myPt;
Storage_Error myErrorStatus;
TCollection_AsciiString myErrorStatusExt;
};
#endif // _StdStorage_TypeData_HeaderFile
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<set>
using namespace std;
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
//基本思想:双指针,与algo里面的set_intersection算法一致
vector<int> res;
set<int> s1,s2;
for(auto num:nums1)
s1.insert(num);
for(auto num:nums2)
s2.insert(num);
set<int>::iterator iter1=s1.begin(),iter2=s2.begin();
while(iter1!=s1.end()&&iter2!=s2.end())
{
if(*iter1==*iter2)
{
res.push_back(*iter1);
iter1++;
iter2++;
}
else if(*iter1>*iter2)
iter2++;
else
iter1++;
}
return res;
}
};
int main()
{
Solution solute;
vector<int> nums1{1,2,2,1};
vector<int> nums2{2,2};
vector<int> nums=solute.intersection(nums1,nums2);
for_each(nums.begin(),nums.end(),[](int n){cout<<n<<endl;});
return 0;
}
|
template<class IntegerType>
struct TRatio {
IntegerType up, down;
explicit TRatio(IntegerType u) : up(u), down(1) {}
TRatio(IntegerType u, IntegerType d) {
assert(d != 0);
const IntegerType g = gcd(u, d);
up = u / g;
down = d / g;
if (down < 0) {
up *= -1;
down *= -1;
}
}
IntegerType gcd(IntegerType a, IntegerType b) {
a = abs(a);
b = abs(b);
while (b) {
a %= b;
swap(a, b);
}
return a;
}
TRatio operator*(int64_t value) const {
return TRatio(up * value, down);
}
TRatio operator+(const TRatio& other) const {
return TRatio(up * other.down + other.up * down, down * other.down);
}
TRatio operator-(const TRatio& other) const {
return TRatio(up * other.down - other.up * down, down * other.down);
}
TRatio operator*(const TRatio& other) const {
return TRatio(up * other.up, down * other.down);
}
TRatio operator/(const TRatio& other) const {
return TRatio(up * other.down, down * other.up);
}
bool operator<(const TRatio& other) const {
return up * other.down < other.up* down;
}
bool operator<=(const TRatio& other) const {
return up * other.down <= other.up * down;
}
};
template<class T>
ostream& operator<<(ostream& os, const TRatio<T>& ratio) {
return os << ratio.up << "/" << ratio.down << "~(" << double(ratio.up) / ratio.down << ")";
}
|
#include "GameGlobal.h"
HINSTANCE GameGlobal::mHInstance = NULL;
HWND GameGlobal::mHwnd = NULL;
LPD3DXSPRITE GameGlobal::mSpriteHandler = NULL;
int GameGlobal::mWidth = 400; //900 test //400
int GameGlobal::mHeight = 225; //600 test //250
int GameGlobal::liveCount = 0;
LPDIRECT3DDEVICE9 GameGlobal::mDevice = nullptr;
bool GameGlobal::isGameRunning = true;
GameGlobal::Song GameGlobal::curSong = GameGlobal::Menu;
IDirect3DSurface9* GameGlobal::backSurface = nullptr;
LPDIRECT3DTEXTURE9 GameGlobal::mAladdintexture = NULL;
LPDIRECT3DTEXTURE9 GameGlobal::mEnemytexture = NULL;
LPDIRECT3DTEXTURE9 GameGlobal::mMaptexture = NULL;
LPDIRECT3DTEXTURE9 GameGlobal::mFlaretexture = NULL;
LPDIRECT3DTEXTURE9 GameGlobal::mCiviliantexture = NULL;
LPDIRECT3DTEXTURE9 GameGlobal::mCameltexture = NULL;
LPDIRECT3DTEXTURE9 GameGlobal::mCayBungtexture = NULL;
LPDIRECT3DTEXTURE9 GameGlobal::mItemtexture = NULL;
LPDIRECT3DTEXTURE9 GameGlobal::mNumbertexture = NULL;
LPDIRECT3DTEXTURE9 GameGlobal::mJafartexture = NULL;
GameGlobal::GameGlobal()
{
liveCount = 3;
if (mSpriteHandler)
{
mSpriteHandler->GetDevice(&GameGlobal::mDevice);
D3DXCreateTextureFromFileExA(
mDevice,
"Resources/Aladdin.png",
1121,
2718,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(255, 0, 255),
NULL,
NULL,
&mAladdintexture);
D3DXCreateTextureFromFileExA(
mDevice,
"Resources/guard.png",
498,
1053,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(120, 193, 152),
NULL,
NULL,
&mEnemytexture);
D3DXCreateTextureFromFileExA(
mDevice,
"Resources/67733.png",
4773,
1383,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(63, 72, 204),
NULL,
NULL,
&mMaptexture);
D3DXCreateTextureFromFileExA(
mDevice,
"Resources/flare.png",
658,
324,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(186, 254, 202),
NULL,
NULL,
&mFlaretexture);
D3DXCreateTextureFromFileExA(
mDevice,
"Resources/civilian.png",
1065,
588,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(120, 193, 152),
NULL,
NULL,
&mCiviliantexture);
D3DXCreateTextureFromFileExA(
mDevice,
"Resources/camel.png",
882,
99,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(248, 0, 248),
NULL,
NULL,
&mCameltexture);
D3DXCreateTextureFromFileExA(
mDevice,
"Resources/cay.png",
171,
36,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(255, 0, 255),
NULL,
NULL,
&mCayBungtexture);
D3DXCreateTextureFromFileExA(
mDevice,
"Resources/item.png",
664,
474,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(248, 0, 248),
NULL,
NULL,
&mItemtexture);
D3DXCreateTextureFromFileExA(
mDevice,
"Resources/number.png",
600,
515,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(255, 0, 255),
NULL,
NULL,
&mNumbertexture);
D3DXCreateTextureFromFileExA(
mDevice,
"Resources/jafar.png",
863,
348,
1,
D3DUSAGE_DYNAMIC,
D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,
D3DX_DEFAULT,
D3DX_DEFAULT,
D3DCOLOR_XRGB(186, 254, 202),
NULL,
NULL,
&mJafartexture);
}
Sound::getInstance()->loadSound("Resources/sound/Aladdin Hurt.wav", "Aladdin Hurt");
Sound::getInstance()->loadSound("Resources/sound/Apple Collect.wav", "Apple Collect");
Sound::getInstance()->loadSound("Resources/sound/Apple Splat.wav", "Apple Splat");
Sound::getInstance()->loadSound("Resources/sound/Camel Spit.wav", "Camel Spit");
Sound::getInstance()->loadSound("Resources/sound/Canopy Bounce.wav", "Canopy Bounce");
Sound::getInstance()->loadSound("Resources/sound/Clay Pot.wav", "Clay Pot");
Sound::getInstance()->loadSound("Resources/sound/Continue Point.wav", "Continue Point");
Sound::getInstance()->loadSound("Resources/sound/Extra Health.wav", "Extra Health");
Sound::getInstance()->loadSound("Resources/sound/Guard Hit 1.wav", "Guard Hit 1");
Sound::getInstance()->loadSound("Resources/sound/Guard Hit 2.wav", "Guard Hit 2");
Sound::getInstance()->loadSound("Resources/sound/Guard's Pants.wav", "Guard's Pants");
Sound::getInstance()->loadSound("Resources/sound/Continue Point.wav", "Continue Point");
Sound::getInstance()->loadSound("Resources/sound/Coming Out.wav", "Coming Out");
Sound::getInstance()->loadSound("Resources/sound/Outta Apples.wav", "Outta Apples");
Sound::getInstance()->loadSound("Resources/sound/Sword Spinning.wav", "Sword Spinning");
Sound::getInstance()->loadSound("Resources/sound/Fire From Coal.wav", "Fire From Coal");
Sound::getInstance()->loadSound("Resources/sound/man1.wav", "background_market");
Sound::getInstance()->loadSound("Resources/sound/chet.wav", "chet");
Sound::getInstance()->loadSound("Resources/sound/Jafar Laugh.wav", "Jafar Laugh");
Sound::getInstance()->loadSound("Resources/sound/Aaah.wav", "Aaah");
Sound::getInstance()->loadSound("Resources/sound/Oooh.wav", "Oooh");
Sound::getInstance()->loadSound("Resources/sound/Jafar Snake.wav", "Jafar Snake");
Sound::getInstance()->loadSound("Resources/sound/Jafar Tractor.wav", "Jafar Tractor");
Sound::getInstance()->loadSound("Resources/sound/bosstheme.wav", "bosstheme");
}
GameGlobal::~GameGlobal()
{
}
void GameGlobal::SetCurrentDevice(LPDIRECT3DDEVICE9 device)
{
mDevice = device;
}
LPDIRECT3DDEVICE9 GameGlobal::GetCurrentDevice()
{
return mDevice;
}
HINSTANCE GameGlobal::GetCurrentHINSTACE()
{
return mHInstance;
}
HWND GameGlobal::getCurrentHWND()
{
return mHwnd;
}
void GameGlobal::SetCurrentHINSTACE(HINSTANCE hInstance)
{
mHInstance = hInstance;
}
void GameGlobal::SetCurrentHWND(HWND hWnd)
{
mHwnd = hWnd;
}
void GameGlobal::SetCurrentSpriteHandler(LPD3DXSPRITE spriteHandler)
{
mSpriteHandler = spriteHandler;
}
LPD3DXSPRITE GameGlobal::GetCurrentSpriteHandler()
{
return mSpriteHandler;
}
void GameGlobal::SetWidth(int width)
{
mWidth = width;
}
int GameGlobal::GetWidth()
{
return mWidth;
}
void GameGlobal::SetHeight(int height)
{
mHeight = height;
}
int GameGlobal::GetHeight()
{
return mHeight;
}
|
#ifndef UNITATTACK_H
#define UNITATTACK_H
#include "../Specifications.h"
#include "../units/Unit.h"
class Unit;
class UnitAttack {
public:
UnitAttack();
virtual ~UnitAttack();
virtual void attack(Unit& enemy, Unit& attacker);
virtual void counterAttack(Unit& enemy, Unit& contrAttacker);
};
#endif // UNITATTACK_H
|
/****************
* These implementations are copied from pgmultilineedit.h. Some changes are
* made to fix some bugs and also to change some behaviour.
* "Change:" and "CHANGE:" tags help you find these changes.
*/
#include <pgapplication.h>
#include "WidgetMultiLineEdit.hh"
#include "WidgetScrollBar.hh"
using namespace std;
WidgetMultiLineEdit::WidgetMultiLineEdit(PG_Widget* parent, const PG_Rect& r, const char* style, int maximumLength)
: PG_LineEdit(parent, r, style, maximumLength) {
// Change: Use our own scroll bar.
// my_vscroll = new PG_ScrollBar(this, PG_Rect(r.w-16,0,16,r.h));
my_vscroll = new WidgetScrollBar(this, PG_Rect(r.w-16,0,16,r.h));
my_isCursorAtEOL = false;
my_allowHiddenCursor = false;
my_firstLine = 0;
my_vscroll->sigScrollPos.connect(slot(*this, &WidgetMultiLineEdit::handleScroll));
my_vscroll->sigScrollTrack.connect(slot(*this, &WidgetMultiLineEdit::handleScroll));
my_vscroll->Hide();
my_mark = -1;
}
/** CHANGE: A SMALL CHANGE MADE HERE. */
bool WidgetMultiLineEdit::handleScroll(PG_ScrollBar* widget, long data) {
SetVPosition(my_vscroll->GetPosition());
// Change: Update screen here.
this->Update();
my_allowHiddenCursor = true;
return true;
}
void WidgetMultiLineEdit::SetVPosition(int line) {
if (line < 0) {
line = 0;
}
if (line > my_vscroll->GetMaxRange()) {
line = my_vscroll->GetMaxRange();
}
my_firstLine = line;
if (my_vscroll->GetPosition() != line) {
my_vscroll->SetPosition(line);
}
Update();
}
/** CHANGE: NEW FUNCTION */
int
WidgetMultiLineEdit::GetVPosition() const
{
return my_firstLine;
}
void WidgetMultiLineEdit::eventBlit(SDL_Surface* surface, const PG_Rect& src, const PG_Rect& dst) {
PG_ThemeWidget::eventBlit(surface, src, dst);
DrawText(dst);
}
void WidgetMultiLineEdit::DrawText(const PG_Rect& dst) {
int _x = 3;
int _y = 3;
// should we draw the cursor ?
if(IsCursorVisible()) {
DrawTextCursor();
}
// figure out the cursor position that we start at
int pos = 0;
for (unsigned int i = 0; i < (unsigned int)my_firstLine; ++i) {
pos += my_textdata[i].size();
}
// draw text
int maxLines = my_height/GetFontSize() + 1;
int endpos, start, end;
int x1 = 0;
Uint16 w = 0;
int offset = 0;
for (unsigned int i = my_firstLine; i < (unsigned int)my_firstLine + maxLines && i < my_textdata.size(); ++i) {
endpos = pos + my_textdata[i].size();
start = (my_cursorPosition < my_mark ? my_cursorPosition : my_mark);
end = (my_cursorPosition >= my_mark ? my_cursorPosition : my_mark);
// check if we are in the highlighted section
if (my_mark != -1 && my_mark != my_cursorPosition && pos <= end && endpos >= start) {
x1 = _x;
offset = 0;
// draw the initial unhighlighted part
if (pos < start) {
string s = my_textdata[i].substr(0, start-pos);
PG_Widget::DrawText(x1, _y, s.c_str());
PG_FontEngine::GetTextSize(s.c_str(), GetFont(), &w);
x1 += w;
offset = start-pos;
}
string middlepart = my_textdata[i].c_str() + offset;
// check if the end part is unhighlighted
if (endpos > end) {
middlepart = middlepart.substr(0, middlepart.size() - (endpos-end));
string s = my_textdata[i].substr(end - pos, my_textdata[i].size() - (end - pos));
PG_FontEngine::GetTextSize(middlepart.c_str(), GetFont(), &w);
PG_Widget::DrawText(x1+w, _y, s.c_str());
}
PG_Color color(GetFontColor());
PG_Color inv_color(255 - color.r, 255 - color.g, 255 - color.b);
SetFontColor(inv_color);
PG_FontEngine::GetTextSize(middlepart.c_str(), GetFont(), &w);
SDL_Rect rect = {static_cast<Sint16>(x + x1),
static_cast<Sint16>(y + _y),
w,
static_cast<Uint16>(GetFontHeight())};
SDL_Surface* screen = PG_Application::GetScreen();
SDL_FillRect(screen, &rect, SDL_MapRGB(screen->format, color.r, color.g, color.b));
PG_Widget::DrawText(x1, _y, middlepart.c_str());
SetFontColor(color);
}
else {
PG_Widget::DrawText(_x, _y, my_textdata[i].c_str());
}
_y += GetFontHeight();
pos += my_textdata[i].size();
}
}
void WidgetMultiLineEdit::DrawTextCursor() {
int x = my_xpos + 1;
int y = my_ypos + 1;
int xpos, ypos;
GetCursorPos(xpos, ypos);
// check for a hidden cursor
if(!my_allowHiddenCursor) {
// scroll up for cursor
while (ypos < 0 && my_firstLine > 0) {
SetVPosition(--my_firstLine);
GetCursorPos(xpos, ypos);
}
// scroll down for cursor
while (ypos + GetFontHeight() > my_height && my_firstLine < my_vscroll->GetMaxRange()) {
SetVPosition(++my_firstLine);
GetCursorPos(xpos, ypos);
}
}
// draw simple cursor
if(my_srfTextCursor == NULL) {
DrawVLine(xpos + 2, ypos + 2, GetFontHeight()-4, PG_Color());
}
// draw a nice cursor bitmap
else {
PG_Rect src, dst;
PG_Rect rect(x + xpos, y + ypos + GetFontHeight()/2 - my_srfTextCursor->h/2,
my_srfTextCursor->w, my_srfTextCursor->h);
GetClipRects(src, dst, rect);
PG_Widget::eventBlit(my_srfTextCursor, src, dst);
}
}
void WidgetMultiLineEdit::FindWordRight() {
unsigned int currentPos = my_cursorPosition;
// step off the initial space
++currentPos;
// find the next space
while (currentPos-1 <= my_text.size() && my_text[currentPos-1] != ' ' && my_text[currentPos-1] != '\n') {
++currentPos;
}
// go to the end of multiple spaces
while (currentPos <= my_text.size() && (my_text[currentPos] == ' ' || my_text[currentPos] == '\n')) {
++currentPos;
}
SetCursorPos(currentPos);
}
void WidgetMultiLineEdit::FindWordLeft() {
unsigned int currentPos = my_cursorPosition;
// step off the initial space(s)
while (currentPos-1 >= 0 && (my_text[currentPos-1] == ' ' || my_text[currentPos-1] == '\n')) {
--currentPos;
}
// find the next space
while (currentPos-1 >= 0 && my_text[currentPos-1] != ' ' && my_text[currentPos-1] != '\n') {
--currentPos;
}
SetCursorPos(currentPos);
}
void WidgetMultiLineEdit::GetCursorTextPosFromScreen(int x, int y, unsigned int& horzOffset, unsigned int& lineOffset) {
// check for an empty text box
if (my_textdata.size() == 0) {
horzOffset = 0;
lineOffset = 0;
return;
}
// get the line number
int ypos = (y - my_ypos - 3) / GetFontHeight() + my_firstLine;
// stay within limits
if (ypos < 0) {
ypos = 0;
}
if ((unsigned int)ypos >= my_textdata.size()) {
ypos = my_textdata.size()-1;
}
unsigned int min = (unsigned int)-1;
unsigned int min_xpos = 0;
// loop through to find the closest x position
string temp;
for (Uint16 i = 0; i <= my_textdata[ypos].size(); ++i) {
// get the string up to that point
temp = my_textdata[ypos].substr(0, i);
// get the distance for that section
Uint16 w;
PG_FontEngine::GetTextSize(temp.c_str(), GetFont(), &w);
unsigned int dist = abs(x - (my_xpos + 3 + w));
// update minimum
if (dist < min) {
min = dist;
min_xpos = i;
}
}
// set return data
horzOffset = min_xpos;
lineOffset = (unsigned int)ypos;
}
void WidgetMultiLineEdit::GetCursorTextPos(unsigned int& horzOffset, unsigned int& lineOffset) {
// check for an empty text box
if (my_textdata.size() == 0) {
horzOffset = 0;
lineOffset = 0;
return;
}
unsigned int currentPos = my_cursorPosition;
unsigned int line = 0;
// cycle through the lines, finding where our cursor lands
for (vector<PG_String>::iterator i = my_textdata.begin(); i != my_textdata.end(); ++i) {
if(currentPos < i->size() || (currentPos <= i->size() && my_isCursorAtEOL)) {
break;
}
currentPos -= i->size();
line++;
}
// if we're too far, assume we're at the end of the string
if (line >= my_textdata.size()) {
line = my_textdata.size()-1;
currentPos = my_textdata[line].size();
}
// if we're too far on this line, assum we're at the end of line
if (currentPos > my_textdata[line].size()) {
currentPos = my_textdata[line].size();
}
horzOffset = currentPos;
lineOffset = line;
}
void WidgetMultiLineEdit::GetCursorPos(int& x, int& y) {
// check for an empty text box
if (my_textdata.size() == 0) {
x = 0;
y = 0;
return;
}
// get the cursor text position
unsigned int currentPos, line;
GetCursorTextPos(currentPos, line);
// now get the x,y position
string temp = my_textdata[line].substr(0, currentPos);
Uint16 w;
PG_FontEngine::GetTextSize(temp.c_str(), GetFont(), &w);
x = w;
y = (line - my_firstLine)*GetFontHeight();
}
void WidgetMultiLineEdit::CreateTextVector(bool bSetupVScroll) {
int w = my_width - 6 - ((my_vscroll->IsVisible() || !my_vscroll->IsHidden()) ? my_vscroll->w : 0);
// now split the text into lines
my_textdata.clear();
unsigned int start = 0, end = 0, last = 0;
do {
Uint16 lineWidth = 0;
PG_String temp = my_text.substr(start, end-start);
PG_FontEngine::GetTextSize(temp.c_str(), GetFont(), &lineWidth);
if (lineWidth > w) {
if (last == start) {
PG_String s = my_text.substr(start, end-start-1);
my_textdata.push_back(s);
start = --end;
}
else {
PG_String s = my_text.substr(start, last-start);
my_textdata.push_back(s);
start = last;
end = last-1;
}
last = start;
}
else if (my_text[end] == ' ') {
last = end+1;
}
else if (my_text[end] == '\n' || my_text[end] == '\0') {
PG_String s = my_text.substr(start, end-start+1);
my_textdata.push_back(s);
start = end+1;
last = start;
}
} while (end++ < my_text.size());
// setup the scrollbar
if(bSetupVScroll) {
SetupVScroll();
}
}
/** CHANGE: FIXED ONE BUG HERE. */
void WidgetMultiLineEdit::SetupVScroll() {
if (my_textdata.size()*GetFontHeight() < my_height) {
my_vscroll->SetRange(0, 0);
my_vscroll->Hide();
SetVPosition(0);
CreateTextVector(false);
}
else {
my_vscroll->SetRange(0, my_textdata.size() - my_height/GetFontHeight());
if (my_firstLine > my_vscroll->GetMaxRange()) {
SetVPosition(my_vscroll->GetMaxRange());
}
// Change: Original if statement causes eternal loops if text area is not
// visible when setting text.
// if (!my_vscroll->IsVisible() || my_vscroll->IsHidden()) {
if (my_vscroll->IsHidden()) {
// scrollbar makes the window less wide, so we have to redo the text
// (note: don't switch these next two lines, unless you like infinite loops)
my_vscroll->Show();
// Change: Of course we have to setup the scroll bar again if we re-create
// the text vector and thus allow the number of lines to change! (that is:
// give parameter true)
CreateTextVector(true);
// CreateTextVector(false);
}
}
}
/** CHANGE: THIS NEW FUNCTION FIXES THE INPUT FOCUS LOST BUG. */
void
WidgetMultiLineEdit::eventInputFocusLost(PG_MessageObject *newfocus)
{
// This fixes the bug: now it doesn't highlight all the text from start
// to cursor.
int y = this->GetVPosition();
int cursor = this->my_cursorPosition;
this->my_mark = -1;
PG_LineEdit::eventInputFocusLost(newfocus);
this->my_cursorPosition = cursor;
this->SetVPosition(y);
}
bool WidgetMultiLineEdit::eventKeyDown(const SDL_KeyboardEvent* key) {
PG_Char c;
if(!IsCursorVisible()) {
return false;
}
SDL_KeyboardEvent key_copy = *key; // copy key structure
PG_Application::TranslateNumpadKeys(&key_copy);
if ((key_copy.keysym.mod & KMOD_SHIFT) && my_mark == -1) {
my_mark = my_cursorPosition;
}
if(key_copy.keysym.mod & KMOD_CTRL) {
switch(key_copy.keysym.sym) {
case SDLK_HOME:
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
SetCursorPos(0);
return true;
case SDLK_END:
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
SetCursorPos(my_text.length());
return true;
case SDLK_RIGHT:
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
FindWordRight();
return true;
case SDLK_LEFT:
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
FindWordLeft();
return true;
case SDLK_UP:
my_allowHiddenCursor = true;
SetVPosition(--my_firstLine);
return true;
case SDLK_DOWN:
my_allowHiddenCursor = true;
SetVPosition(++my_firstLine);
return true;
default:
break;
}
}
else if(key_copy.keysym.mod & (KMOD_ALT | KMOD_META)) {
}
else {
unsigned int currentPos, line;
int x, y;
switch(key_copy.keysym.sym) {
case SDLK_RIGHT:
case SDLK_LEFT:
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
// break here, we still want PG_LineEdit to handle these
break;
case SDLK_UP:
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
GetCursorPos(x, y);
GetCursorTextPosFromScreen(my_xpos + x + 3, my_ypos + y + 3 - GetFontHeight(), currentPos, line);
SetCursorTextPos(currentPos, line);
return true;
case SDLK_DOWN:
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
GetCursorPos(x, y);
GetCursorTextPosFromScreen(my_xpos + x + 3, my_ypos + y + 3 + GetFontHeight(), currentPos, line);
SetCursorTextPos(currentPos, line);
return true;
case SDLK_PAGEUP:
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
GetCursorPos(x, y);
GetCursorTextPosFromScreen(my_xpos + x + 3, my_ypos + y + 3 - (my_height - GetFontHeight()), currentPos, line);
SetCursorTextPos(currentPos, line);
return true;
case SDLK_PAGEDOWN:
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
GetCursorPos(x, y);
GetCursorTextPosFromScreen(my_xpos + x + 3, my_ypos + y + 3 + (my_height - GetFontHeight()), currentPos, line);
SetCursorTextPos(currentPos, line);
return true;
case SDLK_HOME:
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
GetCursorTextPos(currentPos, line);
SetCursorTextPos(0, line);
return true;
case SDLK_END: {
if (!(key_copy.keysym.mod & KMOD_SHIFT)) {
my_mark = -1;
}
GetCursorTextPos(currentPos, line);
int cursorPos = my_textdata[line].size() - (my_textdata[line][my_textdata[line].size()-1] == '\n' ? 1 : 0);
SetCursorTextPos(cursorPos, line);
}
return true;
case SDLK_RETURN:
c = '\n';
InsertChar(&c);
SetCursorPos(my_cursorPosition);
return true;
default:
break;
}
}
SetCursorPos(my_cursorPosition);
return PG_LineEdit::eventKeyDown(key);
}
/** CHANGE: A SMALL CHANGE MADE HERE. */
bool WidgetMultiLineEdit::eventMouseButtonDown(const SDL_MouseButtonEvent* button) {
// check for mousewheel
if ((button->button == 4 || button->button == 5) && my_vscroll->IsVisible()) {
// Change: This fixes the mouse wheel bug: if not scrolled between cursor
// positioning and this moment, the mouse wheel wouldn't let hide the
// cursor. Force to allow hidden cursor fixes the bug.
my_allowHiddenCursor = true;
if (button->button == 4) {
SetVPosition(--my_firstLine);
}
else {
SetVPosition(++my_firstLine);
}
return true;
}
if (!GetEditable()) {
return false;
}
if (!IsCursorVisible()) {
EditBegin();
}
// if we're clicking the scrollbar....
if (my_vscroll->IsVisible() && button->x > my_xpos + my_width - my_vscroll->w) {
return false;
}
if (button->button == 1) {
Uint8* keys = SDL_GetKeyState(NULL);
if (!(keys[SDLK_LSHIFT] || keys[SDLK_RSHIFT])) {
my_mark = -1;
}
unsigned int currentPos, line;
GetCursorTextPosFromScreen(button->x, button->y, currentPos, line);
SetCursorTextPos(currentPos, line);
if (!(keys[SDLK_LSHIFT] || keys[SDLK_RSHIFT])) {
my_mark = my_cursorPosition;
}
}
return true;
}
bool WidgetMultiLineEdit::eventMouseMotion(const SDL_MouseMotionEvent* motion) {
if (motion->state & SDL_BUTTON(1)) {
unsigned int currentPos, line;
GetCursorTextPosFromScreen(motion->x, motion->y, currentPos, line);
SetCursorTextPos(currentPos, line);
}
return PG_LineEdit::eventMouseMotion(motion);
}
bool WidgetMultiLineEdit::eventMouseButtonUp(const SDL_MouseButtonEvent* button) {
if(!GetEditable()) {
return false;
}
if(!IsCursorVisible()) {
EditBegin();
}
return true;
}
void WidgetMultiLineEdit::SetCursorTextPos(unsigned int offset, unsigned int line) {
my_allowHiddenCursor = false;
if (line < 0) {
SetCursorPos(0);
}
else if (line >= my_textdata.size()) {
SetCursorPos(my_text.size());
my_isCursorAtEOL = false;
}
else {
PG_LineEdit::SetCursorPos(ConvertCursorPos(offset, line));
my_isCursorAtEOL = (offset == my_textdata[line].size() && my_textdata[line].size() != 0);
Update();
}
}
int WidgetMultiLineEdit::ConvertCursorPos(unsigned int offset, unsigned int line) {
unsigned int charCount = 0;
for (unsigned int i = 0; i < line; ++i) {
charCount += my_textdata[i].size();
}
return charCount+offset;
}
void WidgetMultiLineEdit::SetCursorPos(int p) {
my_isCursorAtEOL = false;
my_allowHiddenCursor = false;
PG_LineEdit::SetCursorPos(p);
//Update();
}
void WidgetMultiLineEdit::InsertChar(const PG_Char* c) {
my_allowHiddenCursor = false;
if (my_mark != -1 && my_mark != my_cursorPosition) {
DeleteSelection();
}
PG_LineEdit::InsertChar(c);
my_mark = -1;
CreateTextVector();
Update();
}
void WidgetMultiLineEdit::DeleteChar(Uint16 pos) {
my_allowHiddenCursor = false;
if (my_mark != -1 && my_mark != my_cursorPosition) {
Uint16 oldpos = my_cursorPosition;
DeleteSelection();
// check if backspace was pressed
if (pos == oldpos-1) {
my_cursorPosition++;
}
}
else {
PG_LineEdit::DeleteChar(pos);
}
my_mark = -1;
CreateTextVector();
Update();
}
void WidgetMultiLineEdit::DeleteSelection() {
if (my_mark != -1 && my_mark != my_cursorPosition) {
int start = (my_cursorPosition < my_mark ? my_cursorPosition : my_mark);
int end = (my_cursorPosition >= my_mark ? my_cursorPosition : my_mark);
my_text.erase(start, end-start);
if (my_mark < my_cursorPosition) {
SetCursorPos(my_mark);
}
my_mark = -1;
}
}
void WidgetMultiLineEdit::SetText(const char* new_text) {
PG_LineEdit::SetText(new_text);
CreateTextVector();
my_isCursorAtEOL = false;
my_allowHiddenCursor = false;
my_mark = -1;
// SetVPosition(0);
}
|
// Created on: 2015-12-15
// Created by: Varvara POSKONINA
// 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 _SelectMgr_ViewClipRange_HeaderFile
#define _SelectMgr_ViewClipRange_HeaderFile
#include <Bnd_Range.hxx>
#include <Standard_TypeDef.hxx>
#include <Standard_OStream.hxx>
#include <Standard_Dump.hxx>
#include <vector>
class gp_Ax1;
class Graphic3d_SequenceOfHClipPlane;
//! Class for handling depth clipping range.
//! It is used to perform checks in case if global (for the whole view)
//! clipping planes are defined inside of SelectMgr_RectangularFrustum class methods.
class SelectMgr_ViewClipRange
{
public:
//! Creates an empty clip range.
SelectMgr_ViewClipRange()
{
SetVoid();
}
//! Check if the given depth is not within clipping range(s),
//! e.g. TRUE means depth is clipped.
Standard_Boolean IsClipped (const Standard_Real theDepth) const
{
if (myUnclipRange.IsOut (theDepth))
{
return Standard_True;
}
for (size_t aRangeIter = 0; aRangeIter < myClipRanges.size(); ++aRangeIter)
{
if (!myClipRanges[aRangeIter].IsOut (theDepth))
{
return Standard_True;
}
}
return Standard_False;
}
//! Calculates the min not clipped value from the range.
//! Returns FALSE if the whole range is clipped.
Standard_Boolean GetNearestDepth (const Bnd_Range& theRange, Standard_Real& theDepth) const
{
if (!myUnclipRange.IsVoid() && myUnclipRange.IsOut (theRange))
{
return false;
}
Bnd_Range aCommonClipRange;
theRange.GetMin (theDepth);
if (!myUnclipRange.IsVoid() && myUnclipRange.IsOut (theDepth))
{
myUnclipRange.GetMin (theDepth);
}
for (size_t aRangeIter = 0; aRangeIter < myClipRanges.size(); ++aRangeIter)
{
if (!myClipRanges[aRangeIter].IsOut (theDepth))
{
aCommonClipRange = myClipRanges[aRangeIter];
break;
}
}
if (aCommonClipRange.IsVoid())
{
return true;
}
for (size_t aRangeIter = 0; aRangeIter < myClipRanges.size(); ++aRangeIter)
{
if (!aCommonClipRange.IsOut (myClipRanges[aRangeIter]))
{
aCommonClipRange.Add (myClipRanges[aRangeIter]);
}
}
aCommonClipRange.GetMax (theDepth);
return !theRange.IsOut (theDepth);
}
public:
//! Clears clipping range.
void SetVoid()
{
myClipRanges.resize (0);
myUnclipRange = Bnd_Range (RealFirst(), RealLast());
}
//! Add clipping planes. Planes and picking ray should be defined in the same coordinate system.
Standard_EXPORT void AddClippingPlanes (const Graphic3d_SequenceOfHClipPlane& thePlanes,
const gp_Ax1& thePickRay);
//! Returns the main unclipped range; [-inf, inf] by default.
Bnd_Range& ChangeUnclipRange() { return myUnclipRange; }
//! Adds a clipping sub-range (for clipping chains).
void AddClipSubRange (const Bnd_Range& theRange) { myClipRanges.push_back (theRange); }
//! Dumps the content of me into the stream
Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const;
private:
std::vector<Bnd_Range> myClipRanges;
Bnd_Range myUnclipRange;
};
#endif // _SelectMgr_ViewClipRange_HeaderFile
|
#pragma once
#include "afxcmn.h"
#include "afxwin.h"
// CSetServerIpPort 对话框
class CSetServerIpPort : public CDialogEx
{
DECLARE_DYNAMIC(CSetServerIpPort)
public:
CSetServerIpPort(CWnd* pParent = NULL); // 标准构造函数
virtual ~CSetServerIpPort();
// 对话框数据
enum { IDD = IDD_SETSERVERIP };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnIpnFieldchangedServeripaddress(NMHDR *pNMHDR, LRESULT *pResult);
WSADATA wsaData;
DWORD m_ServerIpAddr;
short m_ServerPort;
afx_msg void OnBnClickedOk();
short m_ClientOwnPort;
BOOL IsPortUsed(unsigned long);
};
|
// PWM outputs connected to LED driver circuits
const int giallo1 = 3;//Red LED drive
const int giallo2 = 5;//Green LED drive
const int bianco = 6;//Blue LED drive
const int power = 4; //Always on for soundsensor
const int sensore_suono = 2; //Sensore sonoro attivo basso
// initial value for the variable resistors
long val_giallo1 = 0;
long val_giallo2 = 0;
long val_bianco = 0;
int side_giallo1 = +1;
int side_giallo2 = +1;
int side_bianco = +1;
int wait_time = 50;
int casual = 0;
int count = 0;
bool debug = false;
void setup() {
//Serial
Serial.begin(9600);
if (debug) Serial.println("Inizio\n");
//Pin led
pinMode(giallo1, OUTPUT);
pinMode(giallo2, OUTPUT);
pinMode(bianco, OUTPUT);
pinMode(power, OUTPUT);
digitalWrite(power, HIGH);
//Sensore sonoro
attachInterrupt(digitalPinToInterrupt(sensore_suono), clap, FALLING);
//Valori iniziali led
val_bianco = 0;
val_giallo1 = 0;
val_giallo2 = 128000;
}
void loop() {
//Fade gialli
fade(giallo1, &val_giallo1, &side_giallo1, 2000);
fade(giallo2, &val_giallo2, &side_giallo2, 4000);
//Effetti blink
switch (casual) {
case 1:
//Rapid blink
Serial.println("BLink 80");
rapid_blink(bianco, &val_bianco, 140);
break;
case 2:
//Rapid blink
Serial.println("BLink 40");
rapid_blink(bianco, &val_bianco, 40);
break;
case 3:
//Fade lento
Serial.println("Fade lento");
fade_blink(bianco, &val_bianco, &side_bianco, 5000);
break;
case 4:
//Fade veloce
Serial.println("Fade lento lento");
fade_blink(bianco, &val_bianco, &side_bianco, 2000);
break;
case 5:
//Sempre attivo
Serial.println("Top white");
top_high();
break;
case 6:
//Tutto spento
Serial.println("Bottom low");
bottom_low();
break;
case 7:
//Blink piccolo
Serial.println("Blink 10");
rapid_blink(bianco, &val_bianco, 40);
break;
case 8:
//Rapid blink
Serial.println("Blink 40");
rapid_blink(bianco, &val_bianco, 160);
break;
case 9:
//Fade lentissimo
Serial.println("Fade lentissimo");
fade_blink(bianco, &val_bianco, &side_bianco, 1000);
break;
case -1:
//Clapclap
rapid_blink_clap();
break;
default:
if (casual < 0) {
break;
}
//Generatore colore
casual = random(600);
if (debug) Serial.print("Casual: ");
if (debug) Serial.println(casual);
break;
}
delay(wait_time);
}
void top_high() {
static unsigned long val = 0;
if (count < 50) {
count++;
if(val<255) val +=60;
if (debug) Serial.println(count);
} else {
val = 20;
count = 0;
casual = 0;
}
val_giallo1 = 255000;
val_giallo2 = 255000;
side_giallo1 = -1;
side_giallo2 = -1;
analogWrite(bianco, val);
}
void bottom_low() {
if (count < 50) {
count++;
if(val_bianco>0) val_bianco -=60;
if (debug) Serial.println(count);
} else {
val_bianco = 255;
count = 0;
casual = 0;
}
val_giallo1 = 0;
val_giallo2 = 0;
side_giallo1 = +1;
side_giallo2 = +1;
analogWrite(bianco, val_bianco);
}
void fade(int led, long* value, int* side, long step_value) {
*value += *side * step_value;
if (*value >= 255000) {
*side = -1;
*value = 255000;
} else if (*value <= 20) {
*side = +1;
*value = 20;
}
analogWrite(led, *value / 1000);
}
void fade_blink(int led, long* value, int* side, long step_value) {
if (debug) Serial.print("Fade");
*value += *side * step_value;
if (*value >= 255000) {
*side = -1;
*value = 255000;
} else if (*value <= 0) {
*side = +1;
*value = 20;
casual = 0;
}
analogWrite(led, *value / 1000);
}
void rapid_blink(int led, long* value, int blink_n) {
//Controllo di ciclo
if (count < blink_n) {
count++;
if (debug) Serial.print("Count: ");
if (debug) Serial.println(count);
} else {
Serial.println("End blink");
analogWrite(led, 20);
count = 0;
casual = 0;
return;
}
if(count % 2 != 0) return;
if (*value != 255 && *value != 0) {
*value = 20;
}
if (*value == 255) {
*value = 20;
} else {
*value = 255;
}
analogWrite(led, *value);
}
void rapid_blink_clap() {
//Controllo di ciclo
if (count < 20) {
count++;
if (debug) Serial.print("Count: ");
if (debug) Serial.println(count);
} else {
Serial.println("End blink");
analogWrite(bianco, 20);
count = 0;
casual = 0;
return;
}
if (val_bianco != 255 && val_bianco != 0) {
val_bianco = 20;
}
if (val_bianco == 255) {
val_bianco = 20;
} else {
val_bianco = 255;
}
analogWrite(bianco, val_bianco);
}
void reset_white() {
analogWrite(bianco, 0);
val_bianco = 0;
}
void clap() {
static unsigned long last_interrupt_time = 0;
static unsigned long last_clap = 0;
static int count_clap = 0;
unsigned long interrupt_time = millis();
if (interrupt_time - last_clap > 1000) {
Serial.println("Azzera");
count_clap = 0;
}
if (interrupt_time - last_interrupt_time > 100) {
count_clap++;
Serial.print("Clap: ");
Serial.println(count_clap);
Serial.print("Last clap: ");
Serial.println(last_clap);
Serial.print("Difference clap: ");
Serial.println(interrupt_time - last_clap);
if (count_clap == 1) {
Serial.println("un clap");
last_clap = millis();
}
if (count_clap >= 2) {
Serial.println("due clap");
Serial.print("Span:");
Serial.println(interrupt_time - last_clap);
if (interrupt_time - last_clap < 500) {
Serial.println("Start clap clap");
count = 0;
casual = -1;
reset_white();
}
last_clap = 0;
count_clap = 0;
}
}
last_interrupt_time = interrupt_time;
}
|
#ifndef IMAGEVIEWER_H
#define IMAGEVIEWER_H
#include <QMainWindow>
#include "qaction.h"
#include "qlabel.h"
#include "qmenu.h"
#include "qscrollarea.h"
#include "qscrollbar.h"
#include "qmenubar.h"
#include "qmessagebox.h"
#include "mouselabel.h"
class ImageViewer : public QMainWindow
{
Q_OBJECT
public:
explicit ImageViewer(QWidget *parent = 0);
void setImage(QImage image, double initScale = 0.0);
int getPosX(){ return lround(imageLabel->x / scaleFactor); }
int getPosY(){ return lround(imageLabel->y / scaleFactor); }
MouseLabel *imageLabel;
private slots:
void about();
void zoomIn();
void zoomOut();
void normalSize();
private:
void createActions();
void createMenus();
void scaleImage(double factor);
void adjustScrollBar(QScrollBar *scrollBar, double factor);
QScrollArea *scrollArea;
double scaleFactor;
QAction *zoomInAct;
QAction *zoomOutAct;
QAction *normalSizeAct;
QAction *aboutAct;
QMenu *viewMenu;
QMenu *helpMenu;
};
#endif
|
#pragma once
namespace skybox
{
enum
{
BOX_TOP,
BOX_LEFT,
BOX_RIGHT,
BOX_FRONT,
BOX_BACK,
BOX_BOTTOM
};
void init();
void acquire();
void setTexture(char* name);
void reset();
void render();
void unacquire();
void release();
};
|
#ifndef LATTICE_HEADER
#define LATTICE_HEADER
class Lattice
{
private:
int nd;
int* lattice;
int nc;
int volume; // spatial volume
int lattice_size; // spatial volume * nc
// Pre-allocated space to make is_even more efficient.
int* internal_coord;
public:
Lattice(int my_nd, int* my_lattice, int my_nc)
: nd(my_nd), nc(my_nc)
{
volume = 1;
lattice = new int[my_nd];
for (int mu = 0; mu < my_nd; mu++)
{
volume *= my_lattice[mu];
lattice[mu] = my_lattice[mu];
}
lattice_size = volume*my_nc;
internal_coord = new int[my_nd];
}
Lattice(const Lattice& copy)
: nd(copy.nd), nc(copy.nc), volume(copy.volume), lattice_size(copy.lattice_size)
{
lattice = new int[nd];
for (int mu = 0; mu < nd; mu++)
{
lattice[mu] = copy.lattice[mu];
}
internal_coord = new int[nd];
}
~Lattice()
{
delete[] lattice;
delete[] internal_coord;
}
inline void coord_to_index(int& i, int* coord, int color)
{
int mu;
i = 0;
// Iterate over dimensions
for (mu = nd-1; mu >= 0; mu--)
{
i = i*lattice[mu]+coord[mu];
}
// Factor in color.
i = i*nc + color;
}
inline int coord_to_index(int* coord, int color)
{
int mu;
int i = 0;
// Iterate over dimensions
for (mu = nd-1; mu >= 0; mu--)
{
i = i*lattice[mu]+coord[mu];
}
// Factor in color.
i = i*nc + color;
return i;
}
// Convert from index to coordinate + color.
inline void index_to_coord(int i, int* coord, int& color)
{
int mu;
// Extract the color.
color = i % nc;
i = (i - color)/nc;
// Extract coordinates.
for (mu = 0; mu < nd; mu++)
{
coord[mu] = i % lattice[mu];
i = (i - coord[mu])/lattice[mu];
}
}
// Get the coordinate in a direction from an index.
inline int index_to_coordinate_dir(int i, int mu)
{
// Extract the color.
int color = i % nc;
i = (i - color)/nc;
int retval;
// Extract coordinates.
for (int nu = 0; nu <= mu; nu++)
{
retval = i % lattice[nu];
i = (i - retval)/lattice[nu];
}
return retval;
}
// Get the color from an index.
inline int index_to_color(int i)
{
return i % nc;
}
// Find out if site is even (true) or odd (false)
inline bool index_is_even(int &i)
{
int color = 0;
int tmp = 0;
index_to_coord(i, internal_coord, color);
for (int j = 0; j < nd; j++) { tmp += internal_coord[j]; }
return (tmp+1) % 2;
}
// Find out of coord is even (1) or odd(0)
inline bool coord_is_even(int* coord)
{
int tmp = 0;
for (int j = 0; j < nd; j++) { tmp += coord[j]; }
return tmp % 2;
}
inline void get_lattice(int* lattice)
{
for (int mu = 0; mu < nd; mu++)
{
lattice[mu] = this->lattice[mu];
}
}
// Return the length of dimension mu.
inline int get_lattice_dimension(int mu)
{
if (mu >= 0 && mu < nd)
{
return lattice[mu];
}
else
{
return -1;
}
}
inline int get_nd()
{
return nd;
}
inline int get_nc()
{
return nc;
}
inline int get_volume()
{
return volume;
}
inline int get_lattice_size()
{
return lattice_size;
}
};
#endif // LATTICE_HEADER
|
#include "thread_group.hpp"
#include <csetjmp>
#include <vector>
class jmp_thread_group
: public thread_group
{
public:
template<typename Function>
void launch(int num_threads, Function f)
{
// save the start state
state start_state;
if(!setjmp(start_state))
{
std::clog << "launch(): initializing start state" << std::endl;
// init each thread's state to the start state
thread_state.clear();
thread_state.resize(num_threads, start_state);
set_current_thread_id(0);
}
else
{
// new thread
std::clog << "launch(): jumped to thread " << current_thread_id() << " start state into thread " << std::endl;
}
// execute the thread
f();
std::clog << "launch(): done with thread " << current_thread_id() << std::endl;
barrier();
}
void barrier()
{
std::clog << "barrier(): entering barrier from thread " << current_thread_id() << std::endl;
// save this thread's state
if(!setjmp(thread_state[current_thread_id()]))
{
// switch to the next ready thread
std::clog << "barrier(): jumping from thread " << current_thread_id() << " to thread " << next_current_thread_id() << std::endl;
set_next_current_thread_id();
std::longjmp(thread_state[current_thread_id()], 1);
}
else
{
std::clog << "barrier(): jumped into thread " << current_thread_id() << std::endl;
}
std::clog << "barrier(): thread " << current_thread_id() << " exiting barrier()" << std::endl;
}
virtual int num_threads()
{
return thread_state.size();
}
private:
struct state
{
std::jmp_buf impl;
operator std::jmp_buf &()
{
return impl;
}
operator const std::jmp_buf &() const
{
return impl;
}
};
std::vector<state> thread_state;
};
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
#define INF 0x3f3f3f3f
#define DEVIATION 0.00000005
typedef long long LL;
bool table[MAXN+10][5];
int L[MAXN+10],R[MAXN+10];
int main(int argc, char const *argv[])
{
int kase;
scanf("%d",&kase);
int N,K,num,tmp;
string str;
while( kase-- ){
scanf("%d %d",&N,&K);
memset(table,0,sizeof(table));
for(int i = 0 ; i < K ; i++ ){
scanf("%d",&num);
for(int j = 0 ; j < num ; j++ )
scanf("%d",&L[j]);
for(int j = 0 ; j < num ; j++ )
scanf("%d",&R[j]);
cin >> str;
if( str == "=" ){
for(int j = 0 ; j < num ; j++ )
table[L[j]][1] = table[R[j]][1] = true;
}
else if( str == "<" ){
for(int j = 0 ; j < num ; j++ )
table[L[j]][2] = table[R[j]][3] = true;
}
else if( str == ">" ){
for(int j = 0 ; j < num ; j++ )
table[L[j]][3] = table[R[j]][2] = true;
}
}
for(int i = 1 ; i <= N ; i++ ){
if( table[i][1] || table[i][2] && table[i][3] )
table[i][0] = true;
}
int ans = -1;
for(int i = 1 ; i <= N ; i++ ){
if( table[i][0] == false ){
if( ans == -1 ) ans = i;
else ans = 0;
}
}
printf("%d\n",ans>0?ans:0);
if( kase ) printf("\n");
}
return 0;
}
|
/* -*- 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.
*
* @author Petter Nilsen
*/
#ifndef OP_TOOLBAR_MENU_BUTTON_H
#define OP_TOOLBAR_MENU_BUTTON_H
#include "modules/widgets/OpButton.h"
/***********************************************************************************
** @class OpToolbarMenuButton
** @brief Custom menu that will contain the main menu, but on a toolbar
**
************************************************************************************/
class OpToolbarMenuButton : public OpButton
{
public:
static OP_STATUS Construct(OpToolbarMenuButton** obj, OpButton::ButtonStyle button_style = OpButton::STYLE_IMAGE);
void UpdateButton(OpButton::ButtonStyle button_style);
// == OpWidget ================================
virtual void GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows);
protected:
OpToolbarMenuButton(OpButton::ButtonStyle button_style = OpButton::STYLE_IMAGE);
OpToolbarMenuButton(const OpToolbarMenuButton & menu_button);
virtual ~OpToolbarMenuButton() {}
void Init();
void SetSkin();
// == OpTypedObject ===========================
virtual Type GetType() {return WIDGET_TYPE_TOOLBAR_MENU_BUTTON;}
// == OpInputContext ======================
virtual BOOL OnInputAction(OpInputAction* action);
virtual BOOL IsInputContextAvailable(FOCUS_REASON reason);
// == OpWidget ================================
virtual BOOL OnContextMenu(const OpPoint &point, BOOL keyboard_invoked);
};
#endif // OP_TOOLBAR_MENU_BUTTON_H
|
#include "ThreadPool.h"
using std::thread;
using std::vector;
using std::mutex;
using std::lock_guard;
ThreadPool::ThreadPool(vector<thread>::size_type n) {
// TODO Create vector in initialisation
for (vector<thread>::size_type i(0); i < n; ++i)
threads.push_back(thread(&ThreadPool::thread_loop, this));
}
void ThreadPool::add_job(ThreadPool::job j) {
lock_guard<mutex> lock(jobs_mutex);
jobs.push(j);
}
void ThreadPool::abort(void) {
set_state(ThreadPool::State::Abort);
}
ThreadPool::State ThreadPool::get_state(void) {
lock_guard<mutex> lock(state_mutex);
return state;
}
void ThreadPool::set_state(ThreadPool::State st) {
lock_guard<mutex> lock(state_mutex);
state = st;
}
void ThreadPool::thread_loop(void) {
// TODO Sleep when nothing to do
job j;
while (true) {
ThreadPool::State st = get_state();
if (st == ThreadPool::State::Abort)
return;
{
lock_guard<mutex> lock(jobs_mutex);
if (!jobs.empty()) {
j = jobs.top();
jobs.pop();
}
else if (st == ThreadPool::State::Terminate)
return;
}
if (j) {
j();
j = nullptr;
}
}
}
ThreadPool::~ThreadPool(void) {
set_state(ThreadPool::State::Terminate);
for (auto& t : threads) {
t.join();
}
}
|
#include "Accessory.h"
Accessory::Accessory()
{
}
Accessory::~Accessory()
{
}
void Accessory::Show()
{
cout << "이름 : " << name << endl;
cout << "가격 : " << price << endl;
cout << "마력 : " << stat << endl;
cout << "설명 : " << comment << endl;
cout << "갯수 : ";
if (count == 0)
cout << "매진";
else
cout << count;
cout << endl;
}
void Accessory::InitType()
{
type = MP;
}
|
#ifndef CONFIG_H
#define CONFIG_H
#include <string>
class Config
{
public:
struct Profile
{
int width;
int height;
bool fullscreen;
bool vsync;
bool supersampling;
bool showFPS;
bool fpsProfiling;
};
static Profile profile;
const std::string FILE_PATH = "config.cfg";
void readConfig();
void createDefault();
};
#endif // CONFIG_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2002-2003 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Karlsson
*/
#ifndef WINDOWSLANGUAGEMANAGER_H
#define WINDOWSLANGUAGEMANAGER_H
#include "modules/locale/src/opprefsfilelanguagemanager.h"
/**
* Windows specialization of the locale string manager.
*
* Uses the platform-independent locale string manager, but falls back to
* using the built-in resources if the string could not be loaded from the
* external translation file.
*
* @author Peter Karlsson
*/
class WindowsLanguageManager: public OpPrefsFileLanguageManager
{
public:
WindowsLanguageManager();
virtual ~WindowsLanguageManager() {};
protected:
virtual int GetStringInternalL(int num, OpString &s);
};
#endif // WINDOWSLANGUAGEMANAGER_H
|
/* XMRig
* Copyright (c) 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2020 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 "base/net/tls/ServerTls.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <openssl/ssl.h>
xmrig::ServerTls::ServerTls(SSL_CTX *ctx) :
m_ctx(ctx)
{
}
xmrig::ServerTls::~ServerTls()
{
if (m_ssl) {
SSL_free(m_ssl);
}
}
bool xmrig::ServerTls::isHTTP(const char *data, size_t size)
{
assert(size > 0);
static const char test[6] = "GET /";
return size > 0 && memcmp(data, test, std::min(size, sizeof(test) - 1)) == 0;
}
bool xmrig::ServerTls::isTLS(const char *data, size_t size)
{
assert(size > 0);
static const uint8_t test[3] = { 0x16, 0x03, 0x01 };
return size > 0 && memcmp(data, test, std::min(size, sizeof(test))) == 0;
}
bool xmrig::ServerTls::send(const char *data, size_t size)
{
SSL_write(m_ssl, data, size);
return write(m_write);
}
void xmrig::ServerTls::read(const char *data, size_t size)
{
if (!m_ssl) {
m_ssl = SSL_new(m_ctx);
m_write = BIO_new(BIO_s_mem());
m_read = BIO_new(BIO_s_mem());
SSL_set_accept_state(m_ssl);
SSL_set_bio(m_ssl, m_read, m_write);
}
BIO_write(m_read, data, size);
if (!SSL_is_init_finished(m_ssl)) {
const int rc = SSL_do_handshake(m_ssl);
if (rc < 0 && SSL_get_error(m_ssl, rc) == SSL_ERROR_WANT_READ) {
write(m_write);
} else if (rc == 1) {
write(m_write);
m_ready = true;
read();
}
else {
shutdown();
}
return;
}
read();
}
void xmrig::ServerTls::read()
{
static char buf[16384]{};
int bytes_read = 0;
while ((bytes_read = SSL_read(m_ssl, buf, sizeof(buf))) > 0) {
parse(buf, bytes_read);
}
}
|
// #include <boost/multiprecision/cpp_int.hpp>
// using boost::multiprecision::cpp_int;
#include <bits/stdc++.h>
using namespace std;
// ¯\_(ツ)_/¯
#define f first
#define s second
#define p push
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define foi(i, a, n) for (i = (a); i < (n); ++i)
#define foii(i, a, n) for (i = (a); i <= (n); ++i)
#define fod(i, a, n) for (i = (a); i > (n); --i)
#define fodd(i, a, n) for (i = (a); i >= (n); --i)
#define debug(x) cout << '>' << #x << ':' << x << endl;
#define all(v) v.begin(), v.end()
#define sz(x) ((int)(x).size())
#define endl " \n"
#define newl cout<<"\n"
#define MAXN 100005
#define MOD 1000000007LL
#define EPS 1e-13
#define INFI 1000000000 // 10^9
#define INFLL 1000000000000000000ll //10^18
// ¯\_(ツ)_/¯
//#define l long int
//#define d double
#define ll long long int
#define ull unsigned long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long>
#define vvi vector<vector<int>>
#define vvll vector<vll>
#define vvld vector<vector<ld>>
//vector<vector<int>> v(10, vector<int>(20,500)); 2d vector initialization. of 10 rows and 20 columns, with value 500.
#define mii map<int, int>
#define mll map<long long, long long>
#define pii pair<int, int>
#define pll pair<long long, long long>
#define fast_io() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
ll tc, n, m, k;
// ll ans = 0, c = 0;
// ll i, j;
// ll a, b;
// ll x, y;
ll fact(ll k) {
return (k == 1 ? 1 : k*fact(k-1));
}
ll rightSmall(string& str, char& ch, ll index) {
ll ans = 0;
rep(i, index, sz(str)) if(ch > str[i]) ans++;
return ans;
}
int main()
{
fast_io();
#ifndef ONLINE_JUDGE
freopen("../input.txt", "r", stdin);
freopen("../output.txt", "w", stdout);
#endif
cin>>tc;
while(tc--) {
string str;
cin>>str;
string temp = str;
sort(all(temp));
auto it = unique(all(temp));
int dist = distance(temp.begin(), it);
if(dist != sz(str)) {
cout<<0;
newl;
continue;
}
ll rank = 1;
ll fac = fact(sz(str));
rep(i, 0, sz(str)) {
fac /= (sz(str)-i);
ll count = rightSmall(str, str[i], i+1);
rank += count*fac;
rank %= 1000003;
}
cout<<rank;
newl;
}
return 0;
}
/*
2
4
0 1 0 1
5
0 0 1 0 0
*/
|
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(!head) return nullptr;
ListNode *fhead = new ListNode(head->val+1);
fhead->next = head;
deletion(fhead, head);
return fhead->next;
}
private:
static void deletion(ListNode *fhead, ListNode *head){
if(head == nullptr) return ;
// cout<< fhead->val << head->val<< endl;
if(fhead->val == head->val){
fhead->next = head->next;
delete(head);
deletion(fhead, fhead->next);
}else{
deletion(fhead->next, head->next);
}
}
};
int main(){
ListNode *n1 = new ListNode(1);
ListNode *n2 = new ListNode(1);
ListNode *n3 = new ListNode(2);
ListNode *n4 = new ListNode(3);
ListNode *n5 = new ListNode(3);
n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = n5;
Solution *sol = new Solution();
ListNode *result = sol->deleteDuplicates(n1);
while(result){
cout<< result->val<<endl;
result = result->next;
}
}
|
/*
19.07.20
LG codepro - 데이터 리오더링
*/
#include <iostream>
using namespace std;
unsigned int Make_Data(unsigned int rcv);
// 작성할 함수
unsigned int Make_Data(unsigned int rcv)
{
int sol = 0;
sol = (rcv&15) <<28 ;
sol += ((rcv>>15) & 15) << 24;
sol += ((rcv>>26) & 63) << 18;
sol += ((rcv>>9) & 3)<<16;
sol += ((rcv>>23) & 7 )<<13;
sol += ((rcv>>4) & 31)<<8;
sol += ((rcv>>11) & 15)<<4;
sol += ((rcv>>19) & 15) <<0;
return sol;
}
int main(void)
{
unsigned int rcv=0,sol;
// 입력 받는 부분
cin >> hex >> uppercase >> rcv;
sol = Make_Data(rcv);
cout << hex << uppercase << sol;
}
|
#include <iostream>
#include <cstring>
using namespace std;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
int res=0;
cin>>n>>m;
if (n!=m){
cout<<2;
}
else{
res=m;
for (int i=2;i*i<=m;i++){
if(n%i==0){
res=i;
break;
}
}
cout<<res;
}
}
|
#include "stdafx.h"
#include "QuizPlayer.h"
#include "Quiz.h"
#include "MockQuizView.h"
//#include <vld.h> // Visual Leak Detector. Download and install from http://vld.codeplex.com
using namespace qp;
using namespace std;
struct QuizPlayerTestSuiteFixture
{
QuizPlayerTestSuiteFixture()
:quiz(make_shared<CQuiz>("Quiz title"))
{
}
CQuizPtr quiz;
CMockQuizView mockView;
};
BOOST_FIXTURE_TEST_SUITE(QuizPlayerTests, QuizPlayerTestSuiteFixture)
BOOST_AUTO_TEST_CASE(QuizPlayerCanStartQuiz)
{
CQuizPlayer qp(quiz, mockView);
//BOOST_REQUIRE_NO_THROW(qp.Start());
BOOST_MESSAGE("TODO: implement QuizPlayerTestSuiteFixture");
}
BOOST_AUTO_TEST_SUITE_END()
|
#ifndef __Student__
#define __Student__
#include <iostream>
#include <string>
class Student
{
public:
Student();
Student(
const std::string& first_name,
const std::string& last_name,
const std::string& subject_name,
const int age);
~Student() = default; /* c++ 11 */
void PrintStudentName();
void PrintStudentLastName();
void PrintSubjectName();
void PrintStudentAge();
void PrintInfo();
int GetAge() const;
std::string GetName() const;
std::string GetLastName() const;
private:
int m_age;
std::string m_first_name;
std::string m_last_name;
std::string m_subject_name;
};
#endif
|
//===========================================================================
//! @file scene_toon.h
//! @brief デモシーン トゥーン
//===========================================================================
#pragma once
//===========================================================================
//! @class SceneToon
//===========================================================================
class SceneToon : public DemoSceneBase
{
public:
//-----------------------------------------------------------------------
//! @name 初期化
//-----------------------------------------------------------------------
//@{
//! @brief コンストラクタ
SceneToon() = default;
//! @brief デストラクタ
~SceneToon() override = default;
//@}
private:
//-----------------------------------------------------------------------
//! @name 初期化まとめてるだけ
//-----------------------------------------------------------------------
//@{
//-----------------------------------------------------------------------
//! @brief ライト初期化
//! @return true 正常終了
//! @return false エラー終了
//-----------------------------------------------------------------------
bool initializeLight() override;
//-----------------------------------------------------------------------
//! @brief モデル初期化
//! @return true 正常終了
//! @return false エラー終了
//-----------------------------------------------------------------------
bool initializeModel() override;
//@}
public:
//-----------------------------------------------------------------------
//! @name タスク
//-----------------------------------------------------------------------
//@{
//-----------------------------------------------------------------------
//! @brief 初期化
//! @return true 正常終了
//! @return false エラー終了
//-----------------------------------------------------------------------
bool initialize() override;
//! @brief 更新
void update() override;
//! @brief 描画
void render() override;
//-----------------------------------------------------------------------
//! @brief 描画
//! @param [in] renderMode 描画したいモード
//-----------------------------------------------------------------------
void render(RenderMode renderMode) override;
//! @brief 解放
void cleanup() override;
//@}
private:
std::shared_ptr<gpu::Texture> toonTexture_; //!< トゥーン用テクスチャ
std::shared_ptr<gpu::Texture> modelTexture_; //!< トゥーン用テクスチャ
// モデル
std::unique_ptr<Object> modelFloor_;
std::shared_ptr<Object> modelFbx1_;
std::shared_ptr<Object> modelFbx2_;
};
|
#include "gtest/gtest.h"
#include "../../../../options/Option.hpp"
#include "../../../../options/OptionPut.hpp"
#include "../../../../binomial_method/case/Case.hpp"
#include "../../../../binomial_method/case/Wilmott1Case.hpp"
#include "../../../../binomial_method/method/regular/american/AmericanBinomialMethod.hpp"
double american_putWilmott1(int iT, int iM) {
double T[] = {0.25, 0.5, 0.75, 1.0};
int M[] = {16, 32, 64, 128, 256};
double s0 = 9.;
double r = 0.06;
double E = 10.;
double sigma = 0.3;
OptionPut<double> aOption(T[iT], s0, r, sigma, E);
Wilmott1Case<double> aCase(&aOption, M[iM]);
AmericanBinomialMethod<double> method(&aCase);
method.solve();
double result = method.getResult();
return result;
}
TEST(RegularAmericanPutWilmott1, test16_025) {
double result = american_putWilmott1(0, 0);
EXPECT_NEAR(result, 1.1316, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test32_025) {
double result = american_putWilmott1(0, 1);
EXPECT_NEAR(result, 1.1240, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test64_025) {
double result = american_putWilmott1(0, 2);
EXPECT_NEAR(result, 1.1261, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test128_025) {
double result = american_putWilmott1(0, 3);
EXPECT_NEAR(result, 1.1253, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test256_025) {
double result = american_putWilmott1(0, 4);
EXPECT_NEAR(result, 1.1260, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test16_050) {
double result = american_putWilmott1(1, 0);
EXPECT_NEAR(result, 1.2509, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test32_050) {
double result = american_putWilmott1(1, 1);
EXPECT_NEAR(result, 1.2598, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test64_050) {
double result = american_putWilmott1(1, 2);
EXPECT_NEAR(result, 1.2539, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test128_050) {
double result = american_putWilmott1(1, 3);
EXPECT_NEAR(result, 1.2553, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test256_050) {
double result = american_putWilmott1(1, 4);
EXPECT_NEAR(result, 1.2546, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test16_075) {
double result = american_putWilmott1(2, 0);
EXPECT_NEAR(result, 1.3579, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test32_075) {
double result = american_putWilmott1(2, 1);
EXPECT_NEAR(result, 1.3568, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test64_075) {
double result = american_putWilmott1(2, 2);
EXPECT_NEAR(result, 1.3569, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test128_075) {
double result = american_putWilmott1(2, 3);
EXPECT_NEAR(result, 1.3555, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test256_075) {
double result = american_putWilmott1(2, 4);
EXPECT_NEAR(result, 1.3547, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test16_010) {
double result = american_putWilmott1(3, 0);
EXPECT_NEAR(result, 1.4444, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test32_010) {
double result = american_putWilmott1(3, 1);
EXPECT_NEAR(result, 1.4332, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test64_010) {
double result = american_putWilmott1(3, 2);
EXPECT_NEAR(result, 1.4384, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test128_010) {
double result = american_putWilmott1(3, 3);
EXPECT_NEAR(result, 1.4342, 0.0001);
}
TEST(RegularAmericanPutWilmott1, test256_010) {
double result = american_putWilmott1(3, 4);
EXPECT_NEAR(result, 1.4349, 0.0001);
}
|
#pragma once
namespace Game
{
class Module
{
public:
virtual void update() = 0;
virtual void draw() = 0;
virtual void start() = 0;
virtual void stop() = 0;
virtual void configure() = 0;
virtual void cleanup() = 0;
};
}
|
#pragma once
#include <string>
#include "Sender.h"
using namespace std;
class Mail
{
public:
Mail(string title, string contents, string t);
friend Sender& Sender::operator<<(Mail& mail);
private:
string _title;
string _contents;
string _time;
};
|
#ifndef FIELDDESCRIPTORCONTAINER_H
#define FIELDDESCRIPTORCONTAINER_H
#include <QtGui/QWidget>
#include <QString>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/generated_message_util.h>
template<class Object>
class FieldDescriptorContainer
{
protected:
bool m_subfield;
FieldDescriptorContainer * m_parent;
int m_type;
Object * m_value;
Object * m_defaultValue;
public:
std::string m_name;
google::protobuf::FieldDescriptor * m_field;
virtual QWidget * getWidget(QWidget *parent = 0) = 0;
virtual QWidget * getParent() = 0;
virtual Object * getValue() = 0;
virtual void setValue(Object * value) = 0;
virtual QString toString() = 0;
virtual bool buildMsg(google::protobuf::Message * msg) = 0;
FieldDescriptorContainer(google::protobuf::FieldDescriptor * field)
{
m_field = field;
m_name = field->name();
m_type = field->cpp_type();
//Set the default value depending on type
if(field->has_default_value())
{
switch(field->cpp_type())
{
case google::protobuf::FieldDescriptor::CPPTYPE_BOOL:
{
m_defaultValue = (Object *)field->default_value_bool();
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE:
{
//Note: not sure if this really works. Had to unbox the value from a double into a long
//before converting into the Object type.
m_defaultValue = (Object *) (long) field->default_value_double();
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_ENUM:
{
m_defaultValue = (Object *)field->default_value_enum();
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT:
{
//Note: not sure if this really works. Had to unbox the value from a float into a int
//before converting into the Object type.
m_defaultValue = (Object *) (int) field->default_value_float();
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_INT32:
{
m_defaultValue = (Object *)field->default_value_int32();
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_INT64:
{
m_defaultValue = (Object *)field->default_value_int64();
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE:
{
m_defaultValue = NULL;
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_STRING:
{
m_defaultValue = (Object *)field->default_value_string().c_str();
break;
}
case google::protobuf::FieldDescriptor::CPPTYPE_UINT32:
{
m_defaultValue = (Object *)field->default_value_uint32();
break;
}
default:
{
m_defaultValue = (Object *)field->default_value_uint64();
break;
}
}
}
}
//Destructor
~FieldDescriptorContainer()
{
delete m_field;
delete &m_value;
delete &m_defaultValue;
}
bool isSubField()
{
return m_subfield;
}
void setSubfield(bool sub)
{
m_subfield = sub;
}
void setFieldParent(FieldDescriptorContainer * parent)
{
this->parent = parent;
}
FieldDescriptorContainer * getFieldParent()
{
if(m_subfield)
{
return m_parent;
}
return NULL;
}
};
#endif // FIELDDESCRIPTORCONTAINER_H
|
#pragma once
#include "../Hardware/Registers.hpp"
#include <avr/interrupt.h>
namespace Drivers
{
enum ExternalInterruptPin { i0 = 0, i1 = 2 };
enum ExternalInterruptType { low, change, toLow, toHigh };
template< ExternalInterruptPin Tp, ExternalInterruptType Tt>
class ExternalInterrupt
{
public:
static inline constexpr void init(void)
{
if constexpr ( Tt == ExternalInterruptType::low)
Hardware::RegDef<Hardware::RegName::Mcucr>::setFalse( bitValue(Tp+0) | bitValue(Tp+1) );
if constexpr ( Tt == ExternalInterruptType::change)
{
Hardware::RegDef<Hardware::RegName::Mcucr>::setFalse( bitValue(Tp+1) );
Hardware::RegDef<Hardware::RegName::Mcucr>::setTrue( bitValue(Tp+0) );
}
if constexpr ( Tt == ExternalInterruptType::toLow)
{
Hardware::RegDef<Hardware::RegName::Mcucr>::setFalse( bitValue(Tp+0) );
Hardware::RegDef<Hardware::RegName::Mcucr>::setTrue( bitValue(Tp+1) );
}
if constexpr ( Tt == ExternalInterruptType::low)
Hardware::RegDef<Hardware::RegName::Mcucr>::setTrue( bitValue(Tp+0) | bitValue(Tp+1) );
if constexpr ( Tp == ExternalInterruptPin::i0 )
Hardware::RegDef<Hardware::RegName::Gicr>::setTrue( bitValue( INT0 ) );
if constexpr ( Tp == ExternalInterruptPin::i1 )
Hardware::RegDef<Hardware::RegName::Gicr>::setTrue( bitValue( INT1 ) );
}
static inline void enableAllInterupt() { sei(); }
static inline void disableAllInterupt() { cli(); }
};
}
|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int N, M;
int nCnt = 1;
int nMap[100][100];
int nChecked[100][100];
int dy[4] = { 0, 0, -1, 1 };
int dx[4] = { -1, 1, 0, 0 };
void bfs(int y,int x)
{
queue<pair<int, int>> q;
q.push(make_pair(y, x));
nChecked[y][x] = 1;
while(!q.empty())
{
y = q.front().first;
x = q.front().second;
q.pop();
for (int i = 0; i < 4; i++)
{
int ny = y + dy[i];
int nx = x + dx[i];
if (0 <= ny && ny < N &&
0 <= nx && nx < M )
{
if ((nChecked[ny][nx] == 0) && (nMap[ny][nx] == 1))
{
q.push(make_pair(ny, nx));
nChecked[ny][nx] = nChecked[y][x] + 1;
}
else if (nChecked[ny][nx] == 0)
{
nChecked[ny][nx] = -1;
}
}
}
}
}
int main(void)
{
cin >> N >> M;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
//cin >> nMap[i][j];
scanf("%1d", &nMap[i][j]);
}
}
bfs(0, 0);
cout << nChecked[N-1][M-1] << endl;
return 0;
}
|
namespace iberbar
{
template < typename T >
class TGrowArray
{
public:
TGrowArray( void )
: m_count( 0 )
, m_data( NULL )
{
}
TGrowArray( const TGrowArray& dest )
: m_count( 0 )
, m_data( NULL )
{
if ( dest.m_data )
{
m_data = new T[ dest.m_count ];
memcpy_s( m_data, sizeof( T ) * dest.m_count, dest.m_data, sizeof( T ) * dest.m_count );
m_count = dest.m_count;
}
}
~TGrowArray()
{
clear();
}
public:
/*
* 当resize的尺寸小于已有尺寸,多余的对象会丢失,注意内存是否会泄露
*/
void resize( int count )
{
if ( count == m_count )
return ;
T* lc_new = new T[ count ];
memcpy_s( lc_new, sizeof( T )*count, m_data, sizeof( T )*tMin<uint32>( m_count, count ) );
delete[] m_data;
m_data = lc_new;
m_count = count;
}
void push_back( const T& val )
{
T* lc_new = new T[ m_count + 1 ];
memcpy_s( lc_new, sizeof( T )*( m_count+1 ), m_data, sizeof( T )*m_count );
lc_new[ m_count ] = val;
delete[] m_data;
m_data = lc_new;
m_count ++;
}
void push_front( const T& val )
{
T* lc_new = new T[ m_count + 1 ];
memcpy_s( lc_new+1, sizeof( T )*( m_count+1 ), m_data, sizeof( T )*m_count );
lc_new[ 0 ] = val;
delete[] m_data;
m_data = lc_new;
m_count ++;
}
void insert( uint32 index, const T& val )
{
assert( index < m_count );
T* lc_new = new T[ m_count + 1 ];
memcpy_s( lc_new, sizeof( T )*( m_count+1 ), m_data, sizeof( T )*index );
lc_new[ index ] = val;
memcpy_s( lc_new + index + 1, sizeof( T )*( m_count+1 ), m_data+index, sizeof( T )*( m_count-index ) );
delete[] m_data;
m_data = lc_new;
m_count ++;
}
void remove( uint32 index )
{
assert( index < m_count );
T* lc_new = new T[ m_count-1 ];
memcpy_s( lc_new, sizeof( T )*( m_count-1 ), m_data, sizeof( T )*index );
memcpy_s( lc_new + index, sizeof( T )*( m_count+1 ), m_data+index+1, sizeof( T )*( m_count-index-1 ) );
delete[] m_data;
m_data = lc_new;
m_count --;
}
T pop_back()
{
assert( m_count > 0 );
T lc_pop = m_data[ m_count-1 ];
T* lc_new = new T[ m_count-1 ];
memcpy_s( lc_new, sizeof( T )*( m_count-1 ), m_data, sizeof( T )*( m_count-1 ) );
delete[] m_data;
m_data = lc_new;
m_count --;
return lc_pop;
}
T pop_front()
{
assert( m_count > 0 );
T lc_pop = m_data[ 0 ];
T* lc_new = new T[ m_count - 1 ];
memcpy_s( lc_new, sizeof( T )*( m_count-1 ), m_data+1, sizeof( T )*( m_count-1 ) );
delete[] m_data;
m_data = lc_new;
m_count --;
return lc_pop;
}
void clear()
{
delete[] m_data;
m_data = NULL;
m_count = 0;
}
public:
uint32 size() const
{
return m_count;
}
uint32 get_data( T* pBuf, uint32 nBufSize ) const
{
uint32 lc_copyCount = tMin< uint32 >( nBufSize, m_count );
if ( lc_copyCount > 0 )
memcpy_s( pBuf, nBufSize*sizeof(T), m_data, lc_copyCount*sizeof(T) );
return lc_copyCount;
}
bool empty() const
{
if ( m_count == 0 )
return true;
return false;
}
public:
T& operator[]( uint32 index )
{
assert( index < m_count );
return m_data[ index ];
}
const T& operator[]( uint32 index ) const
{
assert( index < m_count );
return m_data[ index ];
}
private:
uint32 m_count;
T* m_data;
};
}
|
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <iostream>
#include <memory>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
#include <getopt.h>
#include <libgen.h>
#include "perm.h"
#include "perm_group.h"
#include "perm_set.h"
#include "permlib.h"
#include "timer.h"
#include "util.h"
#include "profile_parse.h"
#include "profile_args.h"
#include "profile_read.h"
#include "profile_run.h"
#include "profile_timer.h"
#include "profile_util.h"
namespace
{
std::string progname;
void usage(std::ostream &s)
{
char const *opts[] = {
"[-h|--help]",
"-i|--implementation {gap|mpsym|permlib}",
"[-s|--schreier-sims] {deterministic|random|random-no-guarantee}",
"[-t|--transversals] {explicit|schreier-trees|shallow-schreier-trees}",
"[--check-altsym]",
"[--no-reduce-gens]",
"[-g|--groups GROUPS]",
"[-a|--arch-graph ARCH_GRAPH]",
"[-c|--num-cycles]",
"[-r|--num-runs]",
"[-v|--verbose]",
"[--show-gap-errors]"
};
s << "usage: " << progname << '\n';
for (char const *opt : opts)
s << " " << opt << '\n';
}
struct ProfileOptions
{
VariantOption implementation{"gap", "mpsym", "permlib"};
VariantOption schreier_sims{"deterministic", "random", "random-no-guarantee"};
VariantOption transversals{"explicit", "schreier-trees", "shallow-schreier-trees"};
bool check_altsym = false;
bool no_reduce_gens = false;
bool groups_input = false;
bool arch_graph_input = false;
unsigned num_cycles = 1u;
unsigned num_runs = 1u;
bool verbose = false;
bool show_gap_errors = false;
};
cgtl::BSGS::Options bsgs_options_mpsym(ProfileOptions const &options)
{
using cgtl::BSGS;
BSGS::Options bsgs_options;
if (options.schreier_sims.is("deterministic")) {
bsgs_options.construction = BSGS::Construction::SCHREIER_SIMS;
} else if (options.schreier_sims.is("random")) {
bsgs_options.construction = BSGS::Construction::SCHREIER_SIMS_RANDOM;
} else if (options.schreier_sims.is("random-no-guarantee")) {
bsgs_options.construction = BSGS::Construction::SCHREIER_SIMS_RANDOM;
bsgs_options.schreier_sims_random_guarantee = false;
} else {
throw std::logic_error("unreachable");
}
if (options.transversals.is("explicit"))
bsgs_options.transversals = BSGS::Transversals::EXPLICIT;
else if (options.transversals.is("schreier-trees"))
bsgs_options.transversals = BSGS::Transversals::SCHREIER_TREES;
else if (options.transversals.is("shallow-schreier-trees"))
bsgs_options.transversals = BSGS::Transversals::SHALLOW_SCHREIER_TREES;
else
throw std::logic_error("unreachable");
if (options.check_altsym)
bsgs_options.check_altsym = true;
if (options.no_reduce_gens)
bsgs_options.reduce_gens = false;
return bsgs_options;
}
std::string make_perm_group_gap(gap::PermSet const &generators,
ProfileOptions const &options)
{
std::stringstream ss;
ss << "for i in [1.." << options.num_cycles << "] do\n";
ss << " StabChain(Group(" + generators.permutations + "));\n";
ss << "od;\n";
return ss.str();
}
void make_perm_group_mpsym(cgtl::PermSet const &generators,
ProfileOptions const &options)
{
using cgtl::BSGS;
using cgtl::PermGroup;
using cgtl::PermSet;
auto bsgs_options(bsgs_options_mpsym(options));
for (unsigned i = 0u; i < options.num_cycles; ++i)
PermGroup g(BSGS(generators.degree(), generators, &bsgs_options));
}
template <typename T>
struct TypeTag { using type = T; };
std::variant<
TypeTag<permlib::ExplicitTransversal<permlib::Permutation>>,
TypeTag<permlib::SchreierTreeTransversal<permlib::Permutation>>,
TypeTag<permlib::ShallowSchreierTreeTransversal<permlib::Permutation>>
>
permlib_transversal_type(VariantOption const &transversals)
{
using namespace permlib;
if (transversals.is("explicit"))
return TypeTag<ExplicitTransversal<Permutation>>{};
else if (transversals.is("schreier-trees"))
return TypeTag<SchreierTreeTransversal<Permutation>>{};
else if (transversals.is("shallow-schreier-trees"))
return TypeTag<ShallowSchreierTreeTransversal<Permutation>>{};
else
throw std::logic_error("unreachable");
}
void make_perm_group_permlib(permlib::PermSet const &generators,
ProfileOptions const &options)
{
using namespace permlib;
std::visit([&](auto transv_type_) {
using transv_type = typename decltype(transv_type_)::type;
if (options.schreier_sims.is("deterministic")) {
SchreierSimsConstruction<Permutation, transv_type>
construction(generators.degree);
for (unsigned i = 0; i < options.num_cycles; ++i)
construction.construct(generators.permutations.begin(),
generators.permutations.end());
} else if (options.schreier_sims.is("random")) {
BSGS<Permutation, transv_type> bsgs(generators.degree);
std::unique_ptr<BSGSRandomGenerator<Permutation, transv_type>>
random_generator(new BSGSRandomGenerator<Permutation, transv_type>(bsgs));
RandomSchreierSimsConstruction<Permutation, transv_type>
construction(generators.degree, random_generator.get());
bool guaranteed = true;
for (unsigned i = 0; i < options.num_cycles; ++i)
construction.construct(generators.permutations.begin(),
generators.permutations.end(),
guaranteed);
}
}, permlib_transversal_type(options.transversals));
}
double run_groups(unsigned degree,
std::string const &generators,
ProfileOptions const &options)
{
double t = 0.0;
if (options.implementation.is("gap")) {
auto generators_gap(parse_generators_gap(degree, generators));
auto gap_script(make_perm_group_gap(generators_gap, options));
run_gap(gap_script, options.verbose, !options.show_gap_errors, &t);
} else if (options.implementation.is("mpsym")) {
auto generators_mpsym(parse_generators_mpsym(degree, generators));
run_cpp([&]{ make_perm_group_mpsym(generators_mpsym, options); }, &t);
} else if (options.implementation.is("permlib")) {
auto generators_permlib(parse_generators_permlib(degree, generators));
run_cpp([&]{ make_perm_group_permlib(generators_permlib, options); }, &t);
}
return t;
}
double run_arch_graph(std::string const &arch_graph,
ProfileOptions const &options)
{
using boost::multiprecision::cpp_int;
using cgtl::ArchGraphSystem;
using cgtl::PermSet;
double t = 0.0;
auto ag(ArchGraphSystem::from_lua(arch_graph));
cpp_int num_automorphisms;
PermSet automorphisms_generators;
if (options.implementation.is("gap")) {
auto gap_script("LoadPackage(\"grape\");\n"
"G:=" + ag->to_gap() + ";\n"
"StabChain(G);\n"
"Print(Size(G), \";\");\n"
"Print(GeneratorsOfGroup(G), \"\\n\");\n");
auto gap_output(
compress_gap_output(run_gap(gap_script, true, !options.show_gap_errors, &t)));
auto gap_output_split(split(gap_output, ";"));
num_automorphisms = cpp_int(gap_output_split[0]);
automorphisms_generators = parse_generators_mpsym(0, gap_output_split[1]);
} else if (options.implementation.is("mpsym")) {
auto bsgs_options(bsgs_options_mpsym(options));
run_cpp([&]{ ag->automorphisms(&bsgs_options); }, &t);
num_automorphisms = ag->automorphisms().order();
automorphisms_generators = ag->automorphisms_generators();
} else if (options.implementation.is("permlib")) {
throw std::logic_error("graph automorphisms not supported by permlib");
}
if (options.verbose) {
info("Automorphism group has order:");
info(num_automorphisms);
info("Automorphism generators are:");
info(automorphisms_generators);
}
return t;
}
template<typename FUNC>
void profile_loop(FUNC &&f,
ProfileOptions const &options)
{
std::vector<double> ts(options.num_runs);
for (unsigned r = 0; r < options.num_runs; ++r) {
if (options.verbose && options.num_runs > 1)
debug_progress("Executing run", r + 1, "/", options.num_runs);
ts[r] = f(options);
}
double t_mean, t_stddev;
util::mean_stddev(ts, &t_mean, &t_stddev);
result("Mean:", t_mean, "s");
result("Stddev:", t_stddev, "s");
if (options.verbose && options.num_runs > 1)
debug_progress_done();
if (options.verbose && options.implementation.is("mpsym")) {
debug("Timer dumps:");
debug_timer_dump("strip");
debug_timer_dump("extend base");
debug_timer_dump("update strong gens");
}
}
void profile(Stream &instream,
ProfileOptions const &options)
{
using namespace std::placeholders;
if (options.verbose) {
debug("Implementation:", options.implementation.get());
debug("Schreier-sims variant:", options.schreier_sims.get());
debug("Transversals:", options.transversals.get());
if (options.num_cycles > 1)
debug("Constructions per run:", options.num_cycles);
}
if (options.groups_input) {
foreach_line(instream.stream, [&](std::string const &line, unsigned lineno){
auto group(parse_group(line));
if (options.verbose) {
info("Constructing group", lineno);
info("=> degree", group.degree);
info("=> orders", group.order);
info("=> generators", group.generators);
} else {
info("Constructing group", lineno);
}
profile_loop(std::bind(run_groups, group.degree, group.generators, _1),
options);
});
} else if (options.arch_graph_input) {
info("Constructing automorphism group");
profile_loop(std::bind(run_arch_graph, read_file(instream.stream), _1),
options);
}
}
} // namespace
int main(int argc, char **argv)
{
progname = basename(argv[0]);
struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"implementation", required_argument, 0, 'i'},
{"schreier-sims", required_argument, 0, 's'},
{"transversals", required_argument, 0, 't'},
{"check-altsym", no_argument, 0, 1 },
{"no-reduce-gens", no_argument, 0, 2 },
{"groups", no_argument, 0, 'g'},
{"arch-graph", no_argument, 0, 'a'},
{"num-cyles", required_argument, 0, 'c'},
{"num-runs", required_argument, 0, 'r'},
{"verbose", no_argument, 0, 'v'},
{"show-gap-errors", no_argument, 0, 3 },
{nullptr, 0, nullptr, 0 }
};
ProfileOptions options;
Stream instream;
for (;;) {
int c = getopt_long(argc, argv, "hi:s:t:g:a:c:r:v", long_options, nullptr);
if (c == -1)
break;
try {
switch(c) {
case 'h':
usage(std::cout);
return EXIT_SUCCESS;
case 'i':
options.implementation.set(optarg);
break;
case 's':
options.schreier_sims.set(optarg);
break;
case 't':
options.transversals.set(optarg);
break;
case 1:
options.check_altsym = true;
break;
case 2:
options.no_reduce_gens = true;
break;
case 'g':
OPEN_STREAM(instream, optarg);
options.groups_input = true;
break;
case 'a':
OPEN_STREAM(instream, optarg);
options.arch_graph_input = true;
break;
case 'c':
options.num_cycles = stox<unsigned>(optarg);
break;
case 'r':
options.num_runs = stox<unsigned>(optarg);
break;
case 'v':
options.verbose = true;
TIMER_ENABLE();
break;
case 3:
options.show_gap_errors = true;
break;
default:
return EXIT_FAILURE;
}
} catch (std::invalid_argument const &e) {
error("invalid option argument:", e.what());
return EXIT_FAILURE;
}
}
CHECK_OPTION(options.implementation.is_set(),
"--implementation option is mandatory");
CHECK_OPTION((options.implementation.is("gap") || options.schreier_sims.is_set()),
"--schreier-sims option is mandatory when not using gap");
CHECK_OPTION((options.implementation.is("gap") || options.transversals.is_set()),
"--transversal-storage option is mandatory when not using gap");
CHECK_OPTION(options.groups_input != options.arch_graph_input,
"EITHER --arch-graph OR --groups must be given");
try {
profile(instream, options);
} catch (std::exception const &e) {
error("profiling failed:", e.what());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
// 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 "Common/CommandLine.h"
namespace {
const command_line::arg_descriptor<std::string> arg_wallet_file = { "wallet-file", "Use wallet <arg>", "" };
const command_line::arg_descriptor<std::string> arg_generate_new_wallet = { "generate-new-wallet", "Generate new wallet and save it to <arg>", "" };
const command_line::arg_descriptor<std::string> arg_daemon_address = { "daemon-address", "Use daemon instance at <host>:<port>", "" };
const command_line::arg_descriptor<std::string> arg_daemon_host = { "daemon-host", "Use daemon instance at host <arg> instead of localhost", "" };
const command_line::arg_descriptor<std::string> arg_password = { "password", "Wallet password", "", true };
const command_line::arg_descriptor<uint16_t> arg_daemon_port = { "daemon-port", "Use daemon instance at port <arg> instead of default", 0 };
const command_line::arg_descriptor<uint32_t> arg_log_level = { "set_log", "", logging::INFO, true };
const command_line::arg_descriptor<bool> arg_testnet = { "testnet", "Used to deploy test nets. The daemon must be launched with --testnet flag", false };
const command_line::arg_descriptor< std::vector<std::string> > arg_command = { "command", "" };
const size_t TIMESTAMP_MAX_WIDTH = 32;
const size_t HASH_MAX_WIDTH = 64;
const size_t TOTAL_AMOUNT_MAX_WIDTH = 20;
const size_t FEE_MAX_WIDTH = 14;
const size_t BLOCK_MAX_WIDTH = 7;
const size_t UNLOCK_TIME_MAX_WIDTH = 11;
}
|
// MFC3(2)View.h: CMFC32View 类的接口
//
#pragma once
class CMFC32View : public CView
{
protected: // 仅从序列化创建
CMFC32View() noexcept;
DECLARE_DYNCREATE(CMFC32View)
// 特性
public:
CMFC32Doc* GetDocument() const;
// 操作
public:
// 重写
public:
virtual void OnDraw(CDC* pDC); // 重写以绘制该视图
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
// 实现
public:
virtual ~CMFC32View();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// 生成的消息映射函数
protected:
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
};
#ifndef _DEBUG // MFC3(2)View.cpp 中的调试版本
inline CMFC32Doc* CMFC32View::GetDocument() const
{ return reinterpret_cast<CMFC32Doc*>(m_pDocument); }
#endif
|
#ifndef OUTPUT_H
#define OUTPUT_H
#include "global.h"
class Output {
public:
void save_at(Data *d);
void save_arrivals(vector<Receiver> receivers,const Data &d);
void save_spherical_cuts(const Source &);
void save_err_vs_dist(const Source &);
void save_err_surface(const Source &);
};
#endif
|
#pragma once
#include <cmath>
class PriorityQueue
{
public:
PriorityQueue();
~PriorityQueue();
int Top() { if (rozmiar != 0) return kopiec[0].vertrex; }
void push(int, int *);
void pop();
int extract();
void write();
int size() { return rozmiar; }
bool empty() { if (rozmiar == 0) return true; return false; }
bool isInQueue(int);
struct pole
{
int vertrex;
int * weight;
};
private:
int rozmiar;
int r;
void fixDown(int);
void fixUp();
int Parent(int x) { return floor((x - 1) / 2); }
int LSon(int x) { return 2 * x + 1; }
int RSon(int x) { return 2 * x + 2; }
void floyd();
pole *kopiec;
};
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
main()
{
ll n, x;
while(cin>>n>>x)
{
ll i, j, c=0, k=n;
for(i=1; i<=n; i++)
if(x/i<=n && x%i==0)c++;
cout<<c<<endl;
}
return 0;
}
|
#include "Graph.h"
#include "Edge.h"
#include "Vertex.h"
#include <string>
#include <iostream>
using namespace std;
/**
* @return The number of vertices in the Graph
*/
template <class V, class E>
unsigned int Graph<V,E>::size() const {
// TODO: Part 2
return vertexMap.size();
}
/**
* @return Returns the degree of a given vertex.
* @param v Given vertex to return degree.
*/
template <class V, class E>
unsigned int Graph<V,E>::degree(const V & v) const {
// TODO: Part 2
string str;
for (auto it : vertexMap){
if (it->second == v){
string str = it->second;
}
}
typename std::unordered_map<string, list<edgeListIter>>::iterator edgeIterator = adjList.find(str);
if (edgeIterator == adjList.end()){
return 0;
}
return edgeIterator->second.size();
}
/**
* Inserts a Vertex into the Graph by adding it to the Vertex map and adjacency list
* @param key The key of the Vertex to insert
* @return The inserted Vertex
*/
template <class V, class E>
V & Graph<V,E>::insertVertex(std::string key) {
// TODO: Part 2
// V & v = *(new V(key));
V& newV = *(new V (key));
vertexMap.insert(pair<string, V &>(key, newV));
list<edgeListIter> newList;
adjList.insert(pair<string, list<edgeListIter>>(key, newList));
return newV;
}
/**
* Removes a given Vertex
* @param v The Vertex to remove
*/
template <class V, class E>
void Graph<V,E>::removeVertex(const std::string & key) {
// TODO: Part 2
/*
cout << "edgeList: " << endl;
for (auto it = edgeList.begin(); it != edgeList.end(); it++){
cout << it->get().source() << " -> " << it->get().dest() << endl;
}
cout << "adjList:" << endl;
for (auto it : adjList.at(key)){
cout << it->get().source().key() << " -> " << it->get().dest().key() << endl;
}
*/
// remove from vertexMap
vertexMap.erase(key);
// remove from edgeList
/*
for (auto it : edgeList){
if (it.get().source().key() == key || it.get().dest().key() == key){
edgeList.remove(it);
}
}
*/
for (auto it = edgeList.begin(); it != edgeList.end(); it++){
string begin = it->get().source().key();
string end = it->get().dest().key();
if (key == begin || key == end){
edgeList.erase(it);
// break;
}
}
// remove from adjList
/*
for (auto it : adjList.at(key)){
if (it->get().source().key() == key || it->get().dest().key() == key){
adjList.at(key).remove(it);
}
}
*/
for (auto iter : adjList.at(key)){
if (iter->get().source().key() == key || iter->get().dest().key() == key){
// iter.clear();
adjList.at(key).remove(iter);
// break;
}
}
/*
cout << "____________________________________" << endl;
cout << "edgeList:" << endl;
for (auto it = edgeList.begin(); it != edgeList.end(); it++){
cout << it->get().source() << " -> " << it->get().dest() << endl;
}
cout << "adjList:" << endl;
for (auto it : adjList.at(key)){
cout << it->get().source().key() << " -> " << it->get().dest().key() << endl;
}
*/
}
/**
* Inserts an Edge into the adjacency list
* @param v1 The source Vertex
* @param v2 The destination Vertex
* @return The inserted Edge
*/
template <class V, class E>
E & Graph<V,E>::insertEdge(const V & v1, const V & v2) {
// TODO: Part 2
E & newEdge = *(new E(v1, v2));
edgeList.push_front(newEdge);
adjList.at(v1.key()).push_front(edgeList.begin());
adjList.at(v2.key()).push_front(edgeList.begin());
return newEdge;
}
/**
* Removes an Edge from the Graph
* @param key1 The key of the ource Vertex
* @param key2 The key of the destination Vertex
*/
template <class V, class E>
void Graph<V,E>::removeEdge(const std::string key1, const std::string key2) {
// TODO: Part 2
/*
for (auto it = edgeList.begin(); it != edgeList.end(); it++){
cout << it->get().source() << " -> " << it->get().dest() << endl;
}
*/
/*
for (auto it : adjList.at(key1)){
cout << it->get().source().key() << " -> " << it->get().dest().key() << endl;
}
*/
V v1 (key1);
V v2 (key2);
E edge (v1, v2);
for (auto it = edgeList.begin(); it != edgeList.end(); it++){
V begin = it->get().source();
V end = it->get().dest();
if (v1 == begin && v2 == end){
edgeList.erase(it);
// break;
}
}
// for (auto iter = adjList.at(key1).begin(); iter != adjList.at(key1).end(); iter++){
for (auto iter : adjList.at(key1)){
if (iter->get().source().key() == key1 && iter->get().dest().key() == key2){
// iter.clear();
adjList.at(key1).remove(iter);
// break;
}
}
/*
cout << "fucking shit" << endl;
for (auto it : adjList.at(key1)){
cout << it->get().source().key() << " -> " << it->get().dest().key() << endl;
}
*/
/*
for (auto it = edgeList.begin(); it != edgeList.end(); it++){
cout << it->get().source() << " -> " << it->get().dest() << endl;
}
*/
}
/**
* Removes an Edge from the adjacency list at the location of the given iterator
* @param it An iterator at the location of the Edge that
* you would like to remove
*/
template <class V, class E>
void Graph<V,E>::removeEdge(const edgeListIter & it) {
// TODO: Part 2
string key1 = it->get().source().key();
// for (auto it : adjList.at(key1)){
// cout << it->get().source().key() << " -> " << it->get().dest().key() << endl;
// }
adjList.at(key1).clear();
for (auto it = edgeList.begin(); it != edgeList.end(); it++){
string begin = it->get().source().key();
if (key1 == begin){
edgeList.erase(it);
}
}
//cout << "fucking shit" << endl;
// for (auto it : adjList.at(key1)){
// cout << it->get().source().key() << " -> " << it->get().dest().key() << endl;
// }
}
/**
* @param key The key of an arbitrary Vertex "v"
* @return The list edges (by reference) that are adjacent to "v"
*/
template <class V, class E>
const std::list<std::reference_wrapper<E>> Graph<V,E>::incidentEdges(const std::string key) const {
// TODO: Part 2
std::list<std::reference_wrapper<E>> edges;
/*
typename unordered_map<string, list<edgeListIter>>::const_iterator it = adjList.find(key);
for (auto iter : it->second){
edges.push_back(*iter);
}
*/
for (auto it : adjList.at(key)){
// check if edge destination is NOT the key
if (it->get().dest().key() != key){
edges.push_back(it->get());
}
// check special case:
// if destination is equal to key, it must not be a directed edge
if ((it->get().dest().key() == key) && !it->get().directed()){
edges.push_back(it->get());
}
}
return edges;
}
/**
* Return whether the two vertices are adjacent to one another
* @param key1 The key of the source Vertex
* @param key2 The key of the destination Vertex
* @return True if v1 is adjacent to v2, False otherwise
*/
template <class V, class E>
bool Graph<V,E>::isAdjacent(const std::string key1, const std::string key2) const {
// TODO: Part 2
for (auto & iter : adjList.at(key1)){
// if they are adjacent
if (iter->get().dest().key() == key2){
return true;
}
}
return false;
}
|
#include "Stonewt.h"
#include <iostream>
//enum { Lbs_per_stn = 14 };//pounds per stone
using namespace std;
int main()
{
Stonewt a(30);
cout << a;
Stonewt b(2, 11);
cout << b;
Stonewt c = a + b;
cout << c;
c.setMode(Stonewt::STONE);
cout << c;
c.setMode(Stonewt::FRACTIONAL_POUNDS);
cout << c;
c.setMode(Stonewt::WHOLE_POUNDS);
cout << c;
}
|
#ifndef LED_h
#define LED_h
#include "Arduino.h"
class LED {
public:
LED(int pin);
void on();
void on(int pwm);
void off();
private:
int ledpin;
};
#endif
|
#ifndef MITAMA_ANYHOW_ANYHOW_HPP
#define MITAMA_ANYHOW_ANYHOW_HPP
#include <mitama/anyhow/error.hpp>
#include <mitama/result/detail/fwd.hpp>
#include <memory>
namespace mitama::anyhow {
template <class T>
using result = result<void_to_monostate_t<T>, std::shared_ptr<::mitama::anyhow::error>>;
}
#endif
|
#include <assert.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <reactor/net/Acceptor.h>
#include <reactor/base/SimpleLogger.h>
namespace reactor {
namespace net {
static void default_conn_callback(int fd, const InetAddress &addr, Timestamp time) {
LOG(Info) << "[" << addr.to_string() << "] connected, fd=" << fd << " connect time "
<< time.to_string();
}
Acceptor::Acceptor(EventLoop *loop, const InetAddress &addr):
loop_(loop),
socket_(),
channel_(loop, socket_.fd()),
idle_fd_(::open("/dev/null", O_RDONLY | O_CLOEXEC)),
started_(false),
new_connection_cb_(default_conn_callback) {
assert(idle_fd_ >= 0);
socket_.set_blocking(false);
socket_.set_reuse_addr(true);
socket_.bind(addr);
channel_.set_read_callback(std::bind(&Acceptor::on_read, this));
}
void Acceptor::listen() {
if (!started_) {
socket_.listen(5);
channel_.enable_read();
started_ = true;
}
}
void Acceptor::on_read() {
Timestamp now(Timestamp::current());
InetAddress addr;
int fd = socket_.accept(&addr);
if (fd >= 0) {
new_connection_cb_(fd, addr, now);
} else {
LOG(Error) << "in Acceptor::on_read() " << strerror(errno);
if (errno == EMFILE) {
::close(idle_fd_);
idle_fd_ = socket_.accept(&addr);
::close(idle_fd_);
idle_fd_ = ::open("/dev/null", O_RDONLY | O_CLOEXEC);
}
}
}
} // namespace net
} // namespace reactor
|
#include "gpu_utilities.h"
#include "definitions.h"
#include "jit4ptx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cuda.h>
// Define the pointers to the kernels
CUfunction haddKernel = nullptr;
CUfunction hmodifyKernel = nullptr;
CUfunction haddKernel_part = nullptr;
CUfunction hmodifyKernel_part = nullptr;
// Load PTX file(s) containing the kernels (JIT)
bool load_all_ptx()
{
// Define the name of the ptx
std::string kernelPTX = "kernel.ptx";
CUmodule hmodule = nullptr;
CUlinkState lState = nullptr;
// Load and JIT the ptx - if ok, load the kernels
if (ptxJIT(kernelPTX, &hmodule, &lState, 0))
{
cuModuleGetFunction(&haddKernel, hmodule, "addKernel");
cuModuleGetFunction(&hmodifyKernel, hmodule, "modifyKernel");
cuModuleGetFunction(&haddKernel_part, hmodule, "addKernel_part");
cuModuleGetFunction(&hmodifyKernel_part, hmodule, "modifyKernel_part");
}
else
{
printf("\nFailed to JIT kernels.cu ! \n");
return false;
}
printf(" \n");
return true;
}
// Run on GPU with all the workload in one take
cudaError_t execute_GPU_in_one_take(real* c_from_d, const real* a, const real* b, const size_t nrows, const size_t ncols, const size_t bytes,
const size_t reps, const real dt)
{
// Define necessary variables
cudaError_t exitStat = cudaSuccess;
real* a_d = nullptr;
real* b_d = nullptr;
real* c_d = nullptr;
real* w_d = nullptr;
// Allocate memory on GPU
cudaError_t allocStat = cudaMalloc((void**)&a_d, bytes);
if (allocStat != cudaSuccess)
{
printf("Error allocating a_d... \n");
printf("%s \n", cudaGetErrorString(allocStat));
return allocStat;
}
else
printf("Allocated GPU memory for a_d... \n");
allocStat = cudaMalloc((void**)&b_d, bytes);
if (allocStat != cudaSuccess)
{
printf("Error allocating b_d... \n");
printf("%s \n", cudaGetErrorString(allocStat));
return allocStat;
}
else
printf("Allocated GPU memory for b_d... \n");
allocStat = cudaMalloc((void**)&c_d, bytes);
if (allocStat != cudaSuccess)
{
printf("Error allocating c_d... \n");
printf("%s \n", cudaGetErrorString(allocStat));
return allocStat;
}
else
printf("Allocated GPU memory for c_d... \n");
allocStat = cudaMalloc((void**)&w_d, bytes);
if (allocStat != cudaSuccess)
{
printf("Error allocating w_d... \n");
printf("%s \n", cudaGetErrorString(allocStat));
return allocStat;
}
else
printf("Allocated GPU memory for w_d... \n");
// Init to zero for intermediate array only
cudaMemset(w_d, 0, bytes);
// Everything in one go
dim3 blockSize(BLOCKX, BLOCKY, 1);
dim3 gridSize((ncols + blockSize.x - 1) / blockSize.x, (nrows + blockSize.y - 1) / blockSize.y, 1);
// Transfer data in: 1/2
cudaError_t transferStat = cudaMemcpy(a_d, a, bytes, cudaMemcpyHostToDevice);
if (transferStat != cudaSuccess)
{
printf("Error transferring a -> a_d... \n");
printf("%s \n", cudaGetErrorString(transferStat));
return transferStat;
}
// Transfer data in: 2/2
transferStat = cudaMemcpy(b_d, b, bytes, cudaMemcpyHostToDevice);
if (transferStat != cudaSuccess)
{
printf("Error transferring b -> b_d... \n");
printf("%s \n", cudaGetErrorString(transferStat));
return transferStat;
}
// Workload
for (auto ij = 0; ij < reps; ++ij)
{
// Launch first kernel
//addKernel(real *c, const real *a, const real *b, const size_t rows, const size_t cols, const real dt)
void* args[6] = { &w_d, &a_d, &b_d, (void*)&nrows, (void*)&ncols, (void*)&dt };
cuLaunchKernel(haddKernel, gridSize.x, gridSize.y, gridSize.z, blockSize.x, blockSize.y, blockSize.z, 0, NULL, args, NULL);
// Launch second kernel
//modifyKernel(real* d, const real* a, const real* b, const real* c, const real dt, const size_t rows, const size_t cols)
void* argsM[7] = { &c_d, &a_d, &b_d, &w_d, (void*)&dt, (void*)&nrows, (void*)&ncols };
cuLaunchKernel(hmodifyKernel, gridSize.x, gridSize.y, gridSize.z, blockSize.x, blockSize.y, blockSize.z, 0, NULL, argsM, NULL);
cudaMemcpy(w_d, c_d, bytes, cudaMemcpyDeviceToDevice);
cudaError_t asyncError = cudaGetLastError();
if (asyncError != cudaSuccess)
{
printf("Async Error... \n");
printf("%s \n", cudaGetErrorString(asyncError));
return asyncError;
}
}
// Transfer data out: 1/1
transferStat = cudaMemcpy(c_from_d, c_d, bytes, cudaMemcpyDeviceToHost);
if (transferStat != cudaSuccess)
{
printf("Error transferring c_d -> c_from_d... \n");
printf("%s \n", cudaGetErrorString(transferStat));
return transferStat;
}
// Release resources
cudaFree(a_d);
cudaFree(b_d);
cudaFree(c_d);
cudaFree(w_d);
printf(" \n");
return exitStat;
}
// Run on GPU with all the workload using streams
cudaError_t execute_GPU_with_streams(real* c_from_d, const real* a, const real* b, const size_t bytes, const size_t nrows, const size_t ncols,
const size_t nstreams, const size_t reps, const real dt, const size_t hostPitch, const bool useGPUPitch)
{
// Define necessary variables
cudaError_t exitStat = cudaSuccess;
real* a_d = nullptr;
real* b_d = nullptr;
real* c_d = nullptr;
real* w_d = nullptr;
size_t pitch = 0;
cudaError_t allocStat;
// Allocate memory on GPU
if (useGPUPitch)
allocStat = cudaMallocPitch((void**)&a_d, &pitch, ncols * sizeof(real), nrows);
else
allocStat = cudaMalloc((void**)&a_d, bytes);
if (allocStat != cudaSuccess)
{
printf("Error allocating a_d... \n");
printf("%s \n", cudaGetErrorString(allocStat));
return allocStat;
}
else
printf("Allocated GPU memory for a_d... \n");
if (useGPUPitch)
allocStat = cudaMallocPitch((void**)&b_d, &pitch, ncols * sizeof(real), nrows);
else
allocStat = cudaMalloc((void**)&b_d, bytes);
if (allocStat != cudaSuccess)
{
printf("Error allocating b_d... \n");
printf("%s \n", cudaGetErrorString(allocStat));
return allocStat;
}
else
printf("Allocated GPU memory for b_d... \n");
if (useGPUPitch)
allocStat = cudaMallocPitch((void**)&c_d, &pitch, ncols * sizeof(real), nrows);
else
allocStat = cudaMalloc((void**)&c_d, bytes);
if (allocStat != cudaSuccess)
{
printf("Error allocating c_d... \n");
printf("%s \n", cudaGetErrorString(allocStat));
return allocStat;
}
else
printf("Allocated GPU memory for c_d... \n");
if (useGPUPitch)
allocStat = cudaMallocPitch((void**)&w_d, &pitch, ncols * sizeof(real), nrows);
else
allocStat = cudaMalloc((void**)&w_d, bytes);
if (allocStat != cudaSuccess)
{
printf("Error allocating w_d... \n");
printf("%s \n", cudaGetErrorString(allocStat));
return allocStat;
}
else
printf("Allocated GPU memory for w_d... \n");
// Init to zero for intermediate array only
if (useGPUPitch)
cudaMemset(w_d, 0, pitch * nrows);
else
cudaMemset(w_d, 0, bytes);
// Create the streams as requested...
cudaStream_t* streams = (cudaStream_t*)malloc(nstreams * sizeof(cudaStream_t));
for (int i = 0; i < nstreams; i++) {
cudaStreamCreate(&streams[i]);
}
// Sort out logistics
size_t rowsPerStream = (nrows + nstreams - 1) / nstreams;
size_t colsPerStream = (ncols + nstreams - 1) / nstreams;
unsigned int i_stream = 0;
size_t local_pitch = 0;
if (useGPUPitch)
local_pitch = pitch;
else
local_pitch = ncols * sizeof(real);
// Workload
for (auto irep = 0; irep < reps; ++irep)
{
// Go over the entire array
for (auto ir = 0; ir < nstreams; ++ir)
{
for (auto ic = 0; ic < nstreams; ++ic)
{
// Calculate offsets and size of chunks
size_t nrows_local = rowsPerStream;
size_t ncols_local = colsPerStream;
size_t rowOffset = ir * nrows_local;
size_t colOffset = ic * ncols_local;
// Do not exceed real size of the array
if (rowOffset + nrows_local > nrows)
nrows_local = nrows - rowOffset;
if (colOffset + ncols_local > ncols)
ncols_local = ncols - colOffset;
dim3 block(BLOCKX, BLOCKY, 1);
dim3 grid((ncols_local + block.x - 1) / block.x, (nrows_local + block.y - 1) / block.y, 1);
size_t ioffset = 0;
size_t stride = 0;
if (useGPUPitch)
stride = pitch / sizeof(real);
else
stride = ncols;
ioffset = rowOffset * stride + colOffset;
size_t hoffset = rowOffset * hostPitch + colOffset;
cudaMemcpy2DAsync(&a_d[ioffset], local_pitch, &a[hoffset], hostPitch * sizeof(real), ncols_local * sizeof(real), nrows_local, cudaMemcpyHostToDevice, streams[i_stream]);
cudaMemcpy2DAsync(&b_d[ioffset], local_pitch, &b[hoffset], hostPitch * sizeof(real), ncols_local * sizeof(real), nrows_local, cudaMemcpyHostToDevice, streams[i_stream]);
// Unfortunately, one cannot simply pass the addresses...
real* w_dd = &w_d[ioffset];
real* c_dd = &c_d[ioffset];
real* a_dd = &a_d[ioffset];
real* b_dd = &b_d[ioffset];
//addKernel_part(real* c, const real* a, const real* b, const size_t rows, const size_t cols, const size_t stride, const real dt)
void* args[7] = { (void*)&w_dd, (void*)&a_dd, (void*)&b_dd, (void*)&nrows_local, (void*)&ncols_local, (void*)&stride, (void*)&dt };
CUresult launchErr = cuLaunchKernel(haddKernel_part, grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, streams[i_stream], args, NULL);
if (launchErr != CUDA_SUCCESS)
{
printf("CUresult :: %u \n", launchErr);
return cudaErrorLaunchFailure;
}
//modifyKernel_part(real* d, const real* a, const real* b, const real* c, const real dt, const size_t rows, const size_t cols, const size_t stride)
void* argsM[8] = { (void*)&c_dd, (void*)&a_dd, (void*)&b_dd, (void*)&w_dd, (void*)&dt, (void*)&nrows_local, (void*)&ncols_local, (void*)&stride };
launchErr = cuLaunchKernel(hmodifyKernel_part, grid.x, grid.y, grid.z, block.x, block.y, block.z, 0, streams[i_stream], argsM, NULL);
if (launchErr != CUDA_SUCCESS)
{
printf("CUresult :: %u \n", launchErr);
return cudaErrorLaunchFailure;
}
cudaMemcpy2DAsync(&w_d[ioffset], stride * sizeof(real), &c_d[ioffset], local_pitch, ncols_local * sizeof(real), nrows_local, cudaMemcpyDeviceToDevice, streams[i_stream]);
i_stream = (i_stream + 1) % nstreams;
}
}
}
cudaError_t syncError = cudaMemcpy2D(c_from_d, hostPitch * sizeof(real), c_d, local_pitch, ncols * sizeof(real), nrows, cudaMemcpyDeviceToHost);
if (syncError != cudaSuccess)
{
printf("Error synchronising device... \n");
printf("%s \n", cudaGetErrorString(syncError));
}
// Release resources
for (int i = 0; i < nstreams; i++) {
cudaStreamDestroy(streams[i]);
}
cudaFree(a_d);
cudaFree(b_d);
cudaFree(c_d);
cudaFree(w_d);
printf(" \n");
return syncError;
}
// Run on GPU with the workload partitioned and utilising streams
cudaError_t execute_GPU_chunk_by_chunk(real* c_from_d, const real* a, const real* b, const size_t bytes, const size_t nrows, const size_t ncols,
const size_t nstreams, const size_t nparts, const size_t reps, const real dt, const bool useGPUPitch)
{
cudaError_t exitStat = cudaSuccess;
// Sort out logistics
size_t rowsPerPart = (nrows + nparts - 1) / nparts;
size_t colsPerPart = (ncols + nparts - 1) / nparts;
for (auto irow = 0; irow < nparts; ++irow)
{
for (auto icol = 0; icol < nparts; ++icol)
{
// Calculate offsets and size of chunks
size_t nrows_local = rowsPerPart;
size_t ncols_local = colsPerPart;
size_t rowOffset = irow * nrows_local;
size_t colOffset = icol * ncols_local;
// Do not exceed real size of the array
if (rowOffset + nrows_local > nrows)
nrows_local = nrows - rowOffset;
if (colOffset + ncols_local > ncols)
ncols_local = ncols - colOffset;
size_t ioffset = rowOffset * ncols + colOffset;
execute_GPU_with_streams(&c_from_d[ioffset], &a[ioffset], &b[ioffset], nrows_local * ncols_local * sizeof(real), nrows_local, ncols_local,
nstreams, reps, dt, ncols, useGPUPitch);
}
}
printf(" \n");
return exitStat;
}
// Decide how to partition the matrix
void domain_partitioning(const size_t nrows, const size_t ncols, const size_t narraysReal, const size_t narraysChar, const size_t narraysInt, const size_t narraysBool, const float buffRatio,
size_t& partsRows, size_t& partCols)
{
// Retrieve information on free and total memory of the device
size_t freeMem = 0;
size_t totalMem = 0;
cudaMemGetInfo(&freeMem, &totalMem);
// This is the memory needed in bytes for all the matrices required
const size_t minMemNeedPerElement = (narraysReal * sizeof(real) + narraysChar * sizeof(char) + narraysInt * sizeof(int) + narraysBool * sizeof(bool));
// This is the overall memory needed
const size_t overMemNeed = nrows * ncols * minMemNeedPerElement;
// Does the model fit in memory?
const size_t freeMemAllowed = freeMem * buffRatio;
if (overMemNeed <= freeMemAllowed)
{
partsRows = 1;
partCols = 1;
return;
}
size_t controlDimSize = nrows > ncols ? nrows : ncols;
size_t otherDimSize = nrows * ncols / controlDimSize;
size_t div = 0;
size_t div2 = 0;
while (true)
{
div = divisor(controlDimSize);
if (div * otherDimSize * minMemNeedPerElement <= freeMemAllowed)
{
partsRows = nrows > ncols ? div : otherDimSize;
partCols = nrows * ncols / partsRows;
return;
}
div2 = divisor(otherDimSize);
if (div * div2 * minMemNeedPerElement <= freeMemAllowed)
{
partsRows = nrows > ncols ? div : div2;
partCols = nrows * ncols / partsRows;
return;
}
controlDimSize /= div;
otherDimSize /= div2;
}
}
// Caclulate the max divisor of a number
size_t divisor(size_t number)
{
size_t i;
for (i = 2; i <= sqrt(number); ++i)
{
if (number % i == 0)
return number / i;
}
return 1;
}
// Run a preliminary query to find CUDA-supported devices
bool deviceQuery()
{
int deviceCount = 0;
cudaError_t error_id = cudaGetDeviceCount(&deviceCount);
if (error_id != cudaSuccess) {
printf("cudaGetDeviceCount returned %d\n-> %s\n",
static_cast<int>(error_id), cudaGetErrorString(error_id));
printf("Result = FAIL\n");
return false;
}
// This function call returns 0 if there are no CUDA capable devices.
if (deviceCount == 0)
printf("There are no available device(s) that support CUDA\n");
else
printf("Detected %d CUDA Capable device(s)\n", deviceCount);
int driverVersion = 0, runtimeVersion = 0;
for (auto dev = 0; dev < deviceCount; ++dev)
{
cudaSetDevice(dev);
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, dev);
printf("\nDevice %d: \"%s\"\n", dev, deviceProp.name);
// Console log
cudaDriverGetVersion(&driverVersion);
cudaRuntimeGetVersion(&runtimeVersion);
printf(" CUDA Driver Version / Runtime Version %d.%d / %d.%d\n",
driverVersion / 1000, (driverVersion % 100) / 10,
runtimeVersion / 1000, (runtimeVersion % 100) / 10);
printf(" CUDA Capability Major/Minor version number: %d.%d\n",
deviceProp.major, deviceProp.minor);
char msg[256];
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
sprintf_s(msg, sizeof(msg),
" Total amount of global memory: %.0f MBytes "
"(%llu bytes)\n",
static_cast<float>(deviceProp.totalGlobalMem / 1048576.0f),
(unsigned long long)deviceProp.totalGlobalMem);
#else
snprintf(msg, sizeof(msg),
" Total amount of global memory: %.0f MBytes "
"(%llu bytes)\n",
static_cast<float>(deviceProp.totalGlobalMem / 1048576.0f),
(unsigned long long)deviceProp.totalGlobalMem);
#endif
printf("%s", msg);
printf(
" GPU Max Clock rate: %.0f MHz (%0.2f "
"GHz)\n",
deviceProp.clockRate * 1e-3f, deviceProp.clockRate * 1e-6f);
#if CUDART_VERSION >= 5000
// This is supported in CUDA 5.0 (runtime API device properties)
printf(" Memory Clock rate: %.0f Mhz\n",
deviceProp.memoryClockRate * 1e-3f);
printf(" Memory Bus Width: %d-bit\n",
deviceProp.memoryBusWidth);
if (deviceProp.l2CacheSize) {
printf(" L2 Cache Size: %d bytes\n",
deviceProp.l2CacheSize);
}
#else
// This only available in CUDA 4.0-4.2 (but these were only exposed in the
// CUDA Driver API)
int memoryClock;
getCudaAttribute<int>(&memoryClock, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE,
dev);
printf(" Memory Clock rate: %.0f Mhz\n",
memoryClock * 1e-3f);
int memBusWidth;
getCudaAttribute<int>(&memBusWidth,
CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, dev);
printf(" Memory Bus Width: %d-bit\n",
memBusWidth);
int L2CacheSize;
getCudaAttribute<int>(&L2CacheSize, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, dev);
if (L2CacheSize) {
printf(" L2 Cache Size: %d bytes\n",
L2CacheSize);
}
#endif
printf(
" Maximum Texture Dimension Size (x,y,z) 1D=(%d), 2D=(%d, "
"%d), 3D=(%d, %d, %d)\n",
deviceProp.maxTexture1D, deviceProp.maxTexture2D[0],
deviceProp.maxTexture2D[1], deviceProp.maxTexture3D[0],
deviceProp.maxTexture3D[1], deviceProp.maxTexture3D[2]);
printf(
" Maximum Layered 1D Texture Size, (num) layers 1D=(%d), %d layers\n",
deviceProp.maxTexture1DLayered[0], deviceProp.maxTexture1DLayered[1]);
printf(
" Maximum Layered 2D Texture Size, (num) layers 2D=(%d, %d), %d "
"layers\n",
deviceProp.maxTexture2DLayered[0], deviceProp.maxTexture2DLayered[1],
deviceProp.maxTexture2DLayered[2]);
printf(" Total amount of constant memory: %lu bytes\n",
deviceProp.totalConstMem);
printf(" Total amount of shared memory per block: %lu bytes\n",
deviceProp.sharedMemPerBlock);
printf(" Total number of registers available per block: %d\n",
deviceProp.regsPerBlock);
printf(" Warp size: %d\n",
deviceProp.warpSize);
printf(" Maximum number of threads per multiprocessor: %d\n",
deviceProp.maxThreadsPerMultiProcessor);
printf(" Maximum number of threads per block: %d\n",
deviceProp.maxThreadsPerBlock);
printf(" Max dimension size of a thread block (x,y,z): (%d, %d, %d)\n",
deviceProp.maxThreadsDim[0], deviceProp.maxThreadsDim[1],
deviceProp.maxThreadsDim[2]);
printf(" Max dimension size of a grid size (x,y,z): (%d, %d, %d)\n",
deviceProp.maxGridSize[0], deviceProp.maxGridSize[1],
deviceProp.maxGridSize[2]);
printf(" Maximum memory pitch: %lu bytes\n",
deviceProp.memPitch);
printf(" Texture alignment: %lu bytes\n",
deviceProp.textureAlignment);
printf(
" Concurrent copy and kernel execution: %s with %d copy "
"engine(s)\n",
(deviceProp.deviceOverlap ? "Yes" : "No"), deviceProp.asyncEngineCount);
printf(" Run time limit on kernels: %s\n",
deviceProp.kernelExecTimeoutEnabled ? "Yes" : "No");
printf(" Integrated GPU sharing Host Memory: %s\n",
deviceProp.integrated ? "Yes" : "No");
printf(" Support host page-locked memory mapping: %s\n",
deviceProp.canMapHostMemory ? "Yes" : "No");
printf(" Alignment requirement for Surfaces: %s\n",
deviceProp.surfaceAlignment ? "Yes" : "No");
printf(" Device has ECC support: %s\n",
deviceProp.ECCEnabled ? "Enabled" : "Disabled");
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64)
printf(" CUDA Device Driver Mode (TCC or WDDM): %s\n",
deviceProp.tccDriver ? "TCC (Tesla Compute Cluster Driver)"
: "WDDM (Windows Display Driver Model)");
#endif
printf(" Device supports Unified Addressing (UVA): %s\n",
deviceProp.unifiedAddressing ? "Yes" : "No");
printf(" Device supports Compute Preemption: %s\n",
deviceProp.computePreemptionSupported ? "Yes" : "No");
printf(" Supports Cooperative Kernel Launch: %s\n",
deviceProp.cooperativeLaunch ? "Yes" : "No");
printf(" Supports MultiDevice Co-op Kernel Launch: %s\n",
deviceProp.cooperativeMultiDeviceLaunch ? "Yes" : "No");
printf(" Device PCI Domain ID / Bus ID / location ID: %d / %d / %d\n",
deviceProp.pciDomainID, deviceProp.pciBusID, deviceProp.pciDeviceID);
const char* sComputeMode[] = {
"Default (multiple host threads can use ::cudaSetDevice() with device "
"simultaneously)",
"Exclusive (only one host thread in one process is able to use "
"::cudaSetDevice() with this device)",
"Prohibited (no host thread can use ::cudaSetDevice() with this "
"device)",
"Exclusive Process (many threads in one process is able to use "
"::cudaSetDevice() with this device)",
"Unknown",
NULL };
printf(" Compute Mode:\n");
printf(" < %s >\n", sComputeMode[deviceProp.computeMode]);
}
return true;
}
|
template <typename T>
inline Vector<T,2>::Vector() :
x(0),
y(0)
{
}
template <typename T>
inline Vector<T,2>::Vector(T x, T y) :
x(x),
y(y)
{
}
template <typename T>
inline Vector<T,2>::Vector(std::initializer_list<T> l)
{
assert(l.size() == 2 && "Vector2 must have 2 values\n");
data[0] = l.begin()[0];
data[1] = l.begin()[1];
}
template <typename T>
inline Vector<T,2>::Vector(T v) :
x(v),
y(v)
{
};
template <typename T>
template <typename U>
inline Vector<T,2>::Vector(const Vector<U,2>& v) :
x(static_cast<T>(v.x)),
y(static_cast<T>(v.y))
{
};
template <typename T>
inline Vector<T,2>::~Vector()
{
};
template <typename T>
inline Vector<T,2>& Vector<T,2>::operator = (Vector<T,2> const& v)
{
this->x = v.x;
this->y = v.y;
return *this;
}
template <typename T>
inline T& Vector<T,2>::operator[](UI32 i)
{
assert(i < 2 && "Array Index out of bounds\n");
return this->data[i];
}
template <typename T>
inline const T& Vector<T,2>::operator[](UI32 i) const
{
assert(i < 2 && "Array Index out of bounds\n");
return this->data[i];
}
|
/* -*- 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.
*/
#include "core/pch.h"
#include "modules/encodings/utility/opstring-encodings.h"
#include "modules/encodings/charconverter.h"
#include "modules/encodings/encoders/utf8-encoder.h"
#include "modules/encodings/decoders/utf8-decoder.h"
#include "modules/encodings/decoders/inputconverter.h"
#include "modules/encodings/encoders/outputconverter.h"
#include "modules/encodings/tablemanager/optablemanager.h"
int SetToEncodingL(OpString8 *target, const char *aEncoding, const uni_char *aUTF16str, int aLength)
{
if (NULL == aUTF16str || 0 == aLength)
{
target->Empty();
return 0;
}
OutputConverter *out;
LEAVE_IF_ERROR(OutputConverter::CreateCharConverter(aEncoding, &out));
OpStackAutoPtr<OutputConverter> encoder(out);
return SetToEncodingL(target, encoder.get(), aUTF16str, aLength);
}
int SetToEncodingL(OpString8 *target, OutputConverter *aEncoder, const uni_char *aUTF16str, int aLength)
{
target->Empty();
if (NULL == aUTF16str || 0 == aLength)
return 0;
// Convert the string in chunks, since we cannot determine the size of the
// output string in advance
char buffer[OPSTRING_ENCODE_WORKBUFFER_SIZE]; /* ARRAY OK 2011-08-22 peter */
const char *input = reinterpret_cast<const char *>(aUTF16str);
const size_t givenLength = uni_strlen(aUTF16str);
int input_length = UNICODE_SIZE((aLength == KAll || aLength > static_cast<int>(givenLength)) ? static_cast<int>(givenLength) : aLength);
int processed_bytes;
int written;
int current_pos = 0;
double last_size_factor_used = 0;
while (input_length > 0)
{
written = aEncoder->Convert(input, input_length,
buffer, OPSTRING_ENCODE_WORKBUFFER_SIZE,
&processed_bytes);
if (written == -1)
LEAVE(OpStatus::ERR_NO_MEMORY);
// Stop converting if the last character in the input stream cannot be converted
if (written == 0 && processed_bytes == input_length)
break;
double size_factor = static_cast<double>(written) / processed_bytes;
if (size_factor > last_size_factor_used)
{
int new_length = current_pos + static_cast<int>(op_ceil(input_length * size_factor));
LEAVE_IF_ERROR(target->Grow(new_length));
last_size_factor_used = size_factor;
}
op_strncpy(target->iBuffer + current_pos, buffer, written);
current_pos += written;
input += processed_bytes;
input_length -= processed_bytes;
target->iBuffer[current_pos] = 0;
}
// Make string self-contained
written = aEncoder->ReturnToInitialState(NULL);
if (written > OPSTRING_ENCODE_WORKBUFFER_SIZE)
return aEncoder->GetNumberOfInvalid();
aEncoder->ReturnToInitialState(buffer);
if (written)
target->AppendL(buffer, written);
return aEncoder->GetNumberOfInvalid();
}
OP_STATUS SetFromEncoding(OpString16 *target, const char *aEncoding, const void *aEncodedStr, int aByteLength, int* aInvalidInputs)
{
if (NULL == aEncodedStr)
{
target->Empty();
if (aInvalidInputs)
*aInvalidInputs = 0;
return OpStatus::OK;
}
InputConverter *in;
RETURN_IF_ERROR(InputConverter::CreateCharConverter(aEncoding, &in));
OpAutoPtr<InputConverter> decoder(in);
return SetFromEncoding(target, decoder.get(), aEncodedStr, aByteLength, aInvalidInputs);
}
int SetFromEncodingL(OpString16 *target, const char *aEncoding, const void *aEncodedStr, int aByteLength)
{
int invalid_inputs;
LEAVE_IF_ERROR(SetFromEncoding(target, aEncoding, aEncodedStr, aByteLength, &invalid_inputs));
return invalid_inputs;
}
OP_STATUS SetFromEncoding(OpString16 *target, InputConverter *aDecoder, const void *aEncodedStr, int aByteLength, int* aInvalidInputs)
{
target->Empty();
if (NULL == aEncodedStr)
{
if (aInvalidInputs)
*aInvalidInputs = 0;
return OpStatus::OK;
}
// Convert the string in chunks, since we cannot determine the size of the
// output string in advance
uni_char buffer[UNICODE_DOWNSIZE(OPSTRING_ENCODE_WORKBUFFER_SIZE)]; /* ARRAY OK 2011-08-22 peter */
const char *input = reinterpret_cast<const char *>(aEncodedStr);
int processed_bytes;
int written;
int current_length = target->Length();
while (aByteLength > 0)
{
int new_length = current_length;
written = aDecoder->Convert(input, aByteLength,
buffer, OPSTRING_ENCODE_WORKBUFFER_SIZE,
&processed_bytes);
if (written == -1)
return OpStatus::ERR_NO_MEMORY;
if (written == 0 && processed_bytes == 0)
break;
new_length += UNICODE_DOWNSIZE(written);
if (new_length + 1 > target->Capacity())
{
RETURN_IF_ERROR(target->Grow(2*new_length));
}
uni_char* t = target->iBuffer + current_length;
const uni_char* s = buffer;
for (int i=0; i < UNICODE_DOWNSIZE(written) && *s; ++i)
{
*t++ = *s++;
}
*t = 0;
current_length = new_length;
input += processed_bytes;
aByteLength -= processed_bytes;
}
if (aInvalidInputs)
*aInvalidInputs = aDecoder->GetNumberOfInvalid();
return OpStatus::OK;
}
int SetFromEncodingL(OpString16 *target, InputConverter *aDecoder, const void *aEncodedStr, int aByteLength)
{
int invalid_inputs;
LEAVE_IF_ERROR(SetFromEncoding(target, aDecoder, aEncodedStr, aByteLength, &invalid_inputs));
return invalid_inputs;
}
|
#ifndef FILEMGR_H
#define FILEMGR_H
///////////////////////////////////////////////////////////////////////
// SizeFileMgr.h - Find sizes of files matching specified patterns //
// Ver 1.1 //
// Jim Fawcett, CSE687 - Object Oriented Design, Fall 2018 //
///////////////////////////////////////////////////////////////////////
/*
* Package Operations:
* -------------------
* SizeFileMgr uses the services of FileSystem to find files and stores its findings
* efficiently in DataStore.
* - Finds all files, matching a set of patterns, along with their paths.
* - Stores each fully qualified filename and size, using DataStore.
*
* Required Files:
* ---------------
* SizeFileMgr.h, SizeFileMgr.cpp
* FileSystem.h, FileSystem.cpp,
*
* Maintenance History:
* --------------------
* Ver 1.1 : 10 Aug 2018
* - added reverse display
* - refactored code
* Ver 1.0 : 09 Aug 2018
* - first release
*/
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <functional>
class SizeFileMgr
{
public:
using Path = std::string;
using Pattern = std::string;
using Patterns = std::vector<Pattern>;
using File = std::string;
using Size = size_t;
using DataStore = std::multimap<Size, File, std::greater<Size>>;
using const_iterator = DataStore::const_iterator;
SizeFileMgr(const Path& path);
bool changePath(const Path& path);
void addPattern(const std::string& patt);
void search();
void find(const Path& path);
const_iterator begin() { return store_.begin(); }
const_iterator end() { return store_.end(); }
void display();
bool processCmdLine(int argc, char** argv);
void recursive(bool recurse) { recursive_ = recurse; }
bool isRecursive() { return recursive_; }
void numFiles(size_t num) { numFiles_ = num; }
size_t numFiles() { return numFiles_; }
private:
void showProcessed();
void forwardDisplay();
void reverseDisplay();
Path path_;
Patterns patterns_;
DataStore store_;
bool recursive_ = false;
size_t numFiles_ = 0;
bool reverse_ = false;
size_t largest_ = 0;
size_t smallest_ = 100000000;
};
#endif
|
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_ttf.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_audio.h>
#include <allegro5/allegro_acodec.h>
#include <iostream>
#include <vector>
#include <string>
#include <time.h>
using namespace std;
class Tile {
public:
char cid, pass;
int sy,sx;
void set_values (char,char,int,int);
};
void Tile::set_values(char cid1,char pass1,int sy1,int sx1) {
cid = cid1;
pass = pass1;
sy = sy1;
sx = sx1;
}
class Entity {
public:
int wloc, hloc;
int warp_row, warp_col;
char interact,step_on;
string dialogue,map_warp;
void set_loc(int,int);
void entity_event(string);
void set_warp(string);
void set_hero_loc(int,int);
void cleanup ();
bool action_button;
};
void Entity::cleanup() {
wloc = NULL;
hloc = NULL;
warp_row=NULL;
warp_col=NULL;
interact = NULL;
step_on=NULL;
}
void Entity::set_hero_loc(int row,int col) {
warp_row = row;
warp_col = col;
}
void Entity::set_warp(string map_warp1) {
step_on = 'y';
map_warp = map_warp1;
}
void Entity::set_loc(int wloc1,int hloc1) {
hloc = hloc1;
wloc = wloc1;
}
void Entity::entity_event(string dialogue1) {
interact = 'y';
dialogue = dialogue1;
}
|
#include<iostream>
using namespace std;
class A
{
int i;
public:
// A(){}
// A(int x) : i(x){}
int operator () (int x)
{
i=x;
return i;
}
};
int main()
{
A a;
cout<<a(3)<<endl;
cout<<a(5)<<endl;
}
|
#include <iostream>
#include <bits/stdc++.h>
#define ll long long
using namespace std;
void solve(){
int n;
cin>>n;
vector<int>a(n);
vector<int>b(101);
for(int i=0;i<n;i++) cin>>a[i],b[a[i]]++;
for(int i=0;i<=100;i++){
if(b[i]>0){
cout<<i<<" ";
b[i]--;
}
}
for(int i=0;i<=100;i++){
for(int j=0;j<b[i];j++){
cout<<i<<" ";
}
}
cout<<"\n";
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t;
cin>>t;
for(int i=1;i<=t;i++){
solve();
}
return 0;
}
|
bool ispalindrome(string str,int i,int j){
while(i<j){
if(str[i]!=str[j]) return false;
i++;
j--;
}
return true;
}
int solve(string str,int i,int j,vector<vector<int>>&dp){
if(i>=j) return 0;
if(ispalindrome(str,i,j)) return 0;
if(dp[i][j]!=-1) return dp[i][j];
int ans= INT_MAX;
for(int k=i;k<=j-1;k++){
if(dp[i][k]==-1) dp[i][k]=solve(str,i,k,dp);
if(dp[k+1][j]==-1) dp[k+1][j]=solve(str,k+1,j,dp);
int temp = dp[i][k]+dp[k+1][j]+1;
ans=min(ans,temp);
}
return dp[i][j]=ans;
}
int Solution::minCut(string str) {
vector<vector<int>> dp(str.length()+1,vector<int> (str.length()+1,-1));
return solve(str,0,str.length()-1,dp);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) Opera Software ASA 2009-2011
*
* WebGL GLSL compiler -- pretty printer.
*
*/
#include "core/pch.h"
#ifdef CANVAS3D_SUPPORT
#include "modules/webgl/src/wgl_pretty_printer.h"
/* virtual */ WGL_Decl *
WGL_PrettyPrinter::VisitDecl(WGL_ArrayDecl *d)
{
d->type->VisitType(this);
printer->OutString(" ");
printer->OutString(d->identifier);
OP_ASSERT(d->size && "Got unsized array. Parser shouldn't have let it through.");
if (d->size)
{
printer->OutString("[");
d->size->VisitExpr(this);
printer->OutString("]");
}
else
printer->OutString("[]");
if (d->initialiser)
{
printer->OutString(" = ");
d->initialiser->VisitExpr(this);
}
printer->OutString(";");
return d;
}
/* virtual */ WGL_Decl *
WGL_PrettyPrinter::VisitDecl(WGL_FunctionDefn *d)
{
if (d->head && d->head->GetType() == WGL_Decl::Proto)
static_cast<WGL_FunctionPrototype *>(d->head)->Show(this, FALSE);
printer->OutNewline();
if (d->body)
d->body->VisitStmt(this);
return d;
}
/* virtual */ WGL_Decl *
WGL_PrettyPrinter::VisitDecl(WGL_FunctionPrototype *d)
{
d->Show(this, TRUE);
return d;
}
/* virtual */ WGL_Decl *
WGL_PrettyPrinter::VisitDecl(WGL_InvariantDecl *d)
{
printer->OutString("invariant ");
printer->OutString(d->var_name);
WGL_InvariantDecl *iv = d->next;
while (iv)
{
printer->OutString(", ");
printer->OutString(iv->var_name);
iv = iv->next;
}
printer->OutString(";");
return d;
}
/* virtual */ WGL_Decl *
WGL_PrettyPrinter::VisitDecl(WGL_PrecisionDefn *d)
{
if (printer->ForGLESTarget())
{
printer->OutString("precision ");
// Downgrade precision if we're targeting a non high precision platform.
WGL_Type::Precision prec = d->precision == WGL_Type::High && !printer->ForHighpTarget() ? WGL_Type::Medium : d->precision;
WGL_Type::Show(this, prec);
d->type->VisitType(this);
printer->OutString(";");
printer->OutNewline();
}
return d;
}
/* virtual */ WGL_Decl *
WGL_PrettyPrinter::VisitDecl(WGL_TypeDecl *d)
{
if (d->type)
d->type->VisitType(this);
if (d->var_name)
{
printer->OutString(" ");
printer->OutString(d->var_name);
}
printer->OutString(";");
return d;
}
/* virtual */ WGL_Decl *
WGL_PrettyPrinter::VisitDecl(WGL_VarDecl *d)
{
if (d->type->precision != WGL_Type::NoPrecision && !d->type->implicit_precision)
d->Show(this, !printer->ForGLESTarget()); // Don't show precision qualifiers on desktop.
else
d->Show(this, FALSE);
return d;
}
/* virtual */ WGL_DeclList *
WGL_PrettyPrinter::VisitDeclList(WGL_DeclList *ds)
{
for (WGL_Decl *d = ds->list.First(); d; d = d->Suc())
{
d->VisitDecl(this);
printer->OutNewline();
}
return ds;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_BodyStmt *s)
{
printer->OutString("{");
printer->IncreaseIndent();
printer->OutNewline();
if (s->body)
s->body->VisitStmtList(this);
printer->DecreaseIndent();
printer->OutNewline();
printer->OutString("}");
return s;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_CaseLabel *s)
{
if (s->condition)
{
printer->OutString("case ");
s->condition->VisitExpr(this);
printer->OutString(":");
printer->OutNewline();
}
else
{
printer->OutString("default:");
printer->OutNewline();
}
return s;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_DeclStmt *s)
{
for (WGL_Decl *decl = s->decls.First(); decl; decl = decl->Suc())
{
decl->VisitDecl(this);
if (decl->Suc())
printer->OutNewline();
}
return s;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_DoStmt *s)
{
printer->OutString("do");
printer->OutNewline();
printer->OutString("{");
printer->OutNewline();
printer->IncreaseIndent();
if (s->body)
s->body->VisitStmt(this);
printer->DecreaseIndent();
printer->OutNewline();
printer->OutString("} while (");
if (s->condition)
s->condition->VisitExpr(this);
else
printer->OutString("/*empty*/");
printer->OutString(")");
printer->OutString(";");
return s;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_ExprStmt *s)
{
if (s->expr)
{
s->expr->VisitExpr(this);
printer->OutString(";");
}
return s;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_ForStmt *s)
{
printer->OutString("for (");
if (s->head)
{
s->head->VisitStmt(this);
if (s->head->GetType() == WGL_Stmt::Simple && static_cast<WGL_SimpleStmt *>(s->head)->type == WGL_SimpleStmt::Empty)
printer->OutString(";");
}
if (s->predicate)
s->predicate->VisitExpr(this);
printer->OutString(";");
if (s->update)
s->update->VisitExpr(this);
printer->OutString(")");
if (s->body)
{
if (s->body->GetType() == WGL_Stmt::Body)
{
printer->OutNewline();
s->body->VisitStmt(this);
}
else
{
printer->IncreaseIndent();
printer->OutNewline();
s->body->VisitStmt(this);
printer->DecreaseIndent();
}
}
return s;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_IfStmt *s)
{
printer->OutString("if (");
s->predicate->VisitExpr(this);
printer->OutString(")");
if (s->then_part && s->then_part->GetType() == WGL_Stmt::Body)
{
printer->OutNewline();
s->then_part->VisitStmt(this);
}
else
{
printer->IncreaseIndent();
printer->OutNewline();
if (s->then_part)
s->then_part->VisitStmt(this);
else
printer->OutString(";");
printer->DecreaseIndent();
printer->OutNewline();
}
if (s->else_part)
{
printer->OutNewline();
printer->OutString("else");
printer->OutNewline();
if (s->else_part->GetType() == WGL_Stmt::Body)
s->else_part->VisitStmt(this);
else
{
printer->IncreaseIndent();
s->else_part->VisitStmt(this);
printer->DecreaseIndent();
printer->OutNewline();
}
}
return s;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_ReturnStmt *s)
{
if (s->value)
{
printer->OutString("return (");
s->value->VisitExpr(this);
printer->OutString(");");
}
else
printer->OutString("return;");
return s;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_SimpleStmt *s)
{
switch (s->type)
{
case WGL_SimpleStmt::Empty:
printer->OutString("/*empty*/");
break;
case WGL_SimpleStmt::Default:
printer->OutString("default");
break;
case WGL_SimpleStmt::Continue:
printer->OutString("continue");
break;
case WGL_SimpleStmt::Break:
printer->OutString("break");
break;
case WGL_SimpleStmt::Discard:
printer->OutString("discard");
break;
}
printer->OutString(";");
return s;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_SwitchStmt *s)
{
printer->OutString("switch(");
if (s->scrutinee)
s->scrutinee->VisitExpr(this);
printer->OutString(")");
printer->OutNewline();
printer->OutString("{");
if (s->cases)
s->cases->VisitStmtList(this);
printer->OutNewline();
printer->OutString("}");
printer->OutNewline();
return s;
}
/* virtual */ WGL_Stmt *
WGL_PrettyPrinter::VisitStmt(WGL_WhileStmt *s)
{
printer->OutString("while (");
if (s->condition)
s->condition->VisitExpr(this);
else
printer->OutString("/*empty*/");
printer->OutString(")");
printer->OutNewline();
if (s->body)
s->body->VisitStmt(this);
return s;
}
/* virtual */ WGL_StmtList *
WGL_PrettyPrinter::VisitStmtList(WGL_StmtList *ss)
{
for (WGL_Stmt *s = ss->list.First(); s; s = s->Suc())
{
s->VisitStmt(this);
if (s->Suc() && (s->Suc()->GetType() != WGL_Stmt::Simple || static_cast<WGL_SimpleStmt *>(s->Suc())->type != WGL_SimpleStmt::Empty))
printer->OutNewline();
}
return ss;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_AssignExpr *e)
{
BOOL has_no_prec = printer->HasNoPrecedence();
WGL_Expr::PrecAssoc old_pa = !has_no_prec ? printer->EnterOpScope(WGL_Expr::OpAssign) : static_cast<WGL_Expr::PrecAssoc>(WGL_Expr::PrecLowest);
if (e->lhs)
{
e->lhs->VisitExpr(this);
printer->OutString(" ");
WGL_Op::Show(this, e->op);
printer->OutString("= ");
}
if (e->rhs)
e->rhs->VisitExpr(this);
else
printer->OutString("/*empty*/");
printer->LeaveOpScope(old_pa);
return e;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_BinaryExpr *e)
{
WGL_Expr::PrecAssoc old_pa = printer->EnterOpScope(e->op, printer->GetBinaryArg());
unsigned as_arg = printer->AsBinaryArg(1);
e->arg1->VisitExpr(this);
printer->OutString(" ");
WGL_Op::Show(this, e->op);
printer->OutString(" ");
printer->AsBinaryArg(2);
e->arg2->VisitExpr(this);
printer->LeaveOpScope(old_pa, as_arg);
printer->AsBinaryArg(as_arg);
return e;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_CallExpr *e)
{
if (e->fun)
{
WGL_Expr::PrecAssoc old_pa = printer->EnterOpScope(WGL_Expr::OpCall);
e->fun->VisitExpr(this);
e->args->VisitExprList(this);
printer->LeaveOpScope(old_pa);
}
return e;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_CondExpr *e)
{
WGL_Expr::PrecAssoc old_pa = printer->EnterOpScope(WGL_Expr::OpCond);
e->arg1->VisitExpr(this);
printer->OutString(" ? ");
e->arg2->VisitExpr(this);
printer->OutString(" : ");
e->arg3->VisitExpr(this);
printer->LeaveOpScope(old_pa);
return e;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_IndexExpr *e)
{
if (e->array)
{
WGL_Expr::PrecAssoc old_pa = printer->EnterOpScope(WGL_Expr::OpIndex);
e->array->VisitExpr(this);
printer->OutString("[");
if (e->index)
e->index->VisitExpr(this);
printer->OutString("]");
printer->LeaveOpScope(old_pa);
}
return e;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_LiteralExpr *e)
{
if (e->literal)
e->literal->Show(this);
return e;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_PostExpr *e)
{
WGL_Expr::PrecAssoc old_pa = printer->EnterOpScope(e->op);
e->arg->VisitExpr(this);
WGL_Op::Show(this, e->op);
printer->LeaveOpScope(old_pa);
return e;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_SelectExpr *e)
{
WGL_Expr::PrecAssoc old_pa = printer->EnterOpScope(WGL_Expr::OpFieldSel);
e->value->VisitExpr(this);
printer->OutString(".");
printer->OutString(e->field);
printer->LeaveOpScope(old_pa);
return e;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_SeqExpr *e)
{
WGL_Expr::PrecAssoc old_pa = printer->EnterOpScope(WGL_Expr::OpComma);
e->arg1->VisitExpr(this);
printer->OutString(",");
e->arg2->VisitExpr(this);
printer->LeaveOpScope(old_pa);
return e;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_TypeConstructorExpr *t)
{
t->constructor->VisitType(this);
return t;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_UnaryExpr *e)
{
WGL_Expr::PrecAssoc old_pa = printer->EnterOpScope(e->op);
WGL_Op::Show(this, e->op);
/* Visit the expression if it is not empty/NULL. */
if (e->arg)
e->arg->VisitExpr(this);
printer->LeaveOpScope(old_pa);
return e;
}
/* virtual */ WGL_Expr *
WGL_PrettyPrinter::VisitExpr(WGL_VarExpr *e)
{
if (e->name)
printer->OutString(e->name);
else if (e->const_name)
printer->OutString(e->const_name);
return e;
}
/* virtual */ WGL_ExprList *
WGL_PrettyPrinter::VisitExprList(WGL_ExprList *es)
{
WGL_Expr::PrecAssoc old_pa = printer->EnterArgListScope();
BOOL first = TRUE;
printer->OutString("(");
for (WGL_Expr *e = es->list.First(); e; e = e->Suc())
{
if (!first)
printer->OutString(", ");
else
first = FALSE;
e->VisitExpr(this);
}
printer->OutString(")");
printer->LeaveArgListScope(old_pa);
return es;
}
/* virtual */ WGL_Type *
WGL_PrettyPrinter::VisitType(WGL_ArrayType *t)
{
t->Show(this);
t->element_type->VisitType(this);
if (t->is_constant_value)
{
printer->OutString("[");
printer->OutInt(t->length_value);
printer->OutString("]");
}
else if (!t->length)
{
printer->OutString("[]");
}
else if (t->length_value)
{
printer->OutString("[");
t->length->VisitExpr(this);
printer->OutString("]");
}
return t;
}
/* virtual */ WGL_Type *
WGL_PrettyPrinter::VisitType(WGL_BasicType *t)
{
t->Show(this);
switch(t->type)
{
case WGL_BasicType::Void:
printer->OutString("void");
return t;
case WGL_BasicType::Int:
printer->OutString("int");
return t;
case WGL_BasicType::UInt:
printer->OutString("uint");
return t;
case WGL_BasicType::Bool:
printer->OutString("bool");
return t;
case WGL_BasicType::Float:
printer->OutString("float");
return t;
}
return t;
}
/* virtual */ WGL_Type *
WGL_PrettyPrinter::VisitType(WGL_MatrixType *t)
{
t->Show(this);
switch(t->type)
{
case WGL_MatrixType::Mat2:
printer->OutStringId(UNI_L("mat2"));
return t;
case WGL_MatrixType::Mat3:
printer->OutStringId(UNI_L("mat3"));
return t;
case WGL_MatrixType::Mat4:
printer->OutStringId(UNI_L("mat4"));
return t;
case WGL_MatrixType::Mat2x2:
printer->OutStringId(UNI_L("mat2x2"));
return t;
case WGL_MatrixType::Mat2x3:
printer->OutStringId(UNI_L("mat2x3"));
return t;
case WGL_MatrixType::Mat2x4:
printer->OutStringId(UNI_L("mat2x4"));
return t;
case WGL_MatrixType::Mat3x2:
printer->OutStringId(UNI_L("mat3x2"));
return t;
case WGL_MatrixType::Mat3x3:
printer->OutStringId(UNI_L("mat3x3"));
return t;
case WGL_MatrixType::Mat3x4:
printer->OutStringId(UNI_L("mat3x4"));
return t;
case WGL_MatrixType::Mat4x2:
printer->OutStringId(UNI_L("mat4x2"));
return t;
case WGL_MatrixType::Mat4x3:
printer->OutStringId(UNI_L("mat4x3"));
return t;
case WGL_MatrixType::Mat4x4:
printer->OutStringId(UNI_L("mat4x4"));
return t;
}
return t;
}
/* virtual */ WGL_Type *
WGL_PrettyPrinter::VisitType(WGL_NameType *t)
{
t->Show(this);
printer->OutString(t->name);
return t;
}
/* virtual */ WGL_Type *
WGL_PrettyPrinter::VisitType(WGL_SamplerType *t)
{
t->Show(this);
switch(t->type)
{
case WGL_SamplerType::Sampler1D:
printer->OutStringId(UNI_L("sampler1D"));
return t;
case WGL_SamplerType::Sampler2D:
printer->OutStringId(UNI_L("sampler2D"));
return t;
case WGL_SamplerType::Sampler3D:
printer->OutStringId(UNI_L("sampler3D"));
return t;
case WGL_SamplerType::SamplerCube:
printer->OutStringId(UNI_L("samplerCube"));
return t;
case WGL_SamplerType::Sampler1DShadow:
printer->OutStringId(UNI_L("sampler1DShadow"));
return t;
case WGL_SamplerType::Sampler2DShadow:
printer->OutStringId(UNI_L("sampler2DShadow"));
return t;
case WGL_SamplerType::SamplerCubeShadow:
printer->OutStringId(UNI_L("samplerCubeShadow"));
return t;
case WGL_SamplerType::Sampler1DArray:
printer->OutStringId(UNI_L("sampler1DArray"));
return t;
case WGL_SamplerType::Sampler2DArray:
printer->OutStringId(UNI_L("sampler2DArray"));
return t;
case WGL_SamplerType::Sampler1DArrayShadow:
printer->OutStringId(UNI_L("sampler1DArrayShadow"));
return t;
case WGL_SamplerType::Sampler2DArrayShadow:
printer->OutStringId(UNI_L("sampler2DArrayShadow"));
return t;
case WGL_SamplerType::SamplerBuffer:
printer->OutStringId(UNI_L("samplerBuffer"));
return t;
case WGL_SamplerType::Sampler2DMS:
printer->OutStringId(UNI_L("sampler2DMS"));
return t;
case WGL_SamplerType::Sampler2DMSArray:
printer->OutStringId(UNI_L("sampler2DMSArray"));
return t;
case WGL_SamplerType::Sampler2DRect:
printer->OutStringId(UNI_L("sampler2DRect"));
return t;
case WGL_SamplerType::Sampler2DRectShadow:
printer->OutStringId(UNI_L("sampler2DRectShadow"));
return t;
case WGL_SamplerType::ISampler1D:
printer->OutStringId(UNI_L("isampler1D"));
return t;
case WGL_SamplerType::ISampler2D:
printer->OutStringId(UNI_L("isampler2D"));
return t;
case WGL_SamplerType::ISampler3D:
printer->OutStringId(UNI_L("isampler3D"));
return t;
case WGL_SamplerType::ISamplerCube:
printer->OutStringId(UNI_L("isamplerCube"));
return t;
case WGL_SamplerType::ISampler1DArray:
printer->OutStringId(UNI_L("isampler1DArray"));
return t;
case WGL_SamplerType::ISampler2DArray:
printer->OutStringId(UNI_L("isampler2DArray"));
return t;
case WGL_SamplerType::ISampler2DRect:
printer->OutStringId(UNI_L("isampler2DRect"));
return t;
case WGL_SamplerType::ISamplerBuffer:
printer->OutStringId(UNI_L("isamplerBuffer"));
return t;
case WGL_SamplerType::ISampler2DMS:
printer->OutStringId(UNI_L("isampler2DMS"));
return t;
case WGL_SamplerType::ISampler2DMSArray:
printer->OutStringId(UNI_L("isampler2DMSArray"));
return t;
case WGL_SamplerType::USampler1D:
printer->OutStringId(UNI_L("usampler1D"));
return t;
case WGL_SamplerType::USampler2D:
printer->OutStringId(UNI_L("usampler2D"));
return t;
case WGL_SamplerType::USampler3D:
printer->OutStringId(UNI_L("usampler3D"));
return t;
case WGL_SamplerType::USamplerCube:
printer->OutStringId(UNI_L("usamplerCube"));
return t;
case WGL_SamplerType::USampler1DArray:
printer->OutStringId(UNI_L("usampler1DArray"));
return t;
case WGL_SamplerType::USampler2DArray:
printer->OutStringId(UNI_L("usampler2DArray"));
return t;
case WGL_SamplerType::USampler2DRect:
printer->OutStringId(UNI_L("usampler2DRect"));
return t;
case WGL_SamplerType::USamplerBuffer:
printer->OutStringId(UNI_L("usamplerBuffer"));
return t;
case WGL_SamplerType::USampler2DMS:
printer->OutStringId(UNI_L("usampler2DMS"));
return t;
case WGL_SamplerType::USampler2DMSArray:
printer->OutStringId(UNI_L("usampler2DMS"));
return t;
}
return t;
}
/* virtual */ WGL_Type *
WGL_PrettyPrinter::VisitType(WGL_StructType *t)
{
t->Show(this);
printer->OutString("struct ");
if (t->tag)
printer->OutString(t->tag);
printer->OutNewline();
printer->OutString("{");
printer->IncreaseIndent();
printer->OutNewline();
if (t->fields)
t->fields->VisitFieldList(this);
printer->DecreaseIndent();
printer->OutNewline();
printer->OutString("}");
return t;
}
/* virtual */ WGL_Type *
WGL_PrettyPrinter::VisitType(WGL_VectorType *t)
{
t->Show(this);
switch (t->type)
{
case WGL_VectorType::Vec2:
printer->OutStringId(UNI_L("vec2"));
return t;
case WGL_VectorType::Vec3:
printer->OutStringId(UNI_L("vec3"));
return t;
case WGL_VectorType::Vec4:
printer->OutStringId(UNI_L("vec4"));
return t;
case WGL_VectorType::BVec2:
printer->OutStringId(UNI_L("bvec2"));
return t;
case WGL_VectorType::BVec3:
printer->OutStringId(UNI_L("bvec3"));
return t;
case WGL_VectorType::BVec4:
printer->OutStringId(UNI_L("bvec4"));
return t;
case WGL_VectorType::IVec2:
printer->OutStringId(UNI_L("ivec2"));
return t;
case WGL_VectorType::IVec3:
printer->OutStringId(UNI_L("ivec3"));
return t;
case WGL_VectorType::IVec4:
printer->OutStringId(UNI_L("ivec4"));
return t;
case WGL_VectorType::UVec2:
printer->OutStringId(UNI_L("uvec2"));
return t;
case WGL_VectorType::UVec3:
printer->OutStringId(UNI_L("uvec3"));
return t;
case WGL_VectorType::UVec4:
printer->OutStringId(UNI_L("uvec4"));
return t;
}
return t;
}
/* virtual */ WGL_Field *
WGL_PrettyPrinter::VisitField(WGL_Field *f)
{
WGL_Type *t = f->type;
BOOL is_array = FALSE;
while (t->GetType() == WGL_Type::Array)
{
is_array = TRUE;
t = static_cast<WGL_ArrayType *>(t)->element_type;
}
if (t->GetType() == WGL_Type::Struct)
{
OP_ASSERT(static_cast<WGL_StructType*>(t)->tag);
printer->OutString(static_cast<WGL_StructType*>(t)->tag);
}
else
t->VisitType(this);
printer->OutString(" ");
printer->OutString(f->name);
if (is_array)
WGL_ArrayType::ShowSizes(this, static_cast<WGL_ArrayType *>(f->type));
return f;
}
/* virtual */ WGL_FieldList *
WGL_PrettyPrinter::VisitFieldList(WGL_FieldList *fs)
{
for (WGL_Field *f = fs->list.First(); f; f = f->Suc())
{
f->VisitField(this);
printer->OutString(";");
if (f->Suc())
printer->OutNewline();
}
return fs;
}
/* virtual */ WGL_Param *
WGL_PrettyPrinter::VisitParam(WGL_Param *p)
{
WGL_Param::Show(this, p->direction);
if (p->direction != WGL_Param::None)
printer->OutString(" ");
p->type->VisitType(this);
if (p->name)
{
printer->OutString(" ");
printer->OutString(p->name);
}
return p;
}
/* virtual */ WGL_ParamList *
WGL_PrettyPrinter::VisitParamList(WGL_ParamList *ps)
{
BOOL first = TRUE;
for (WGL_Param *p = ps->list.First(); p; p = p->Suc())
{
if (!first)
printer->OutString(", ");
else
first = FALSE;
p->VisitParam(this);
}
return ps;
}
/* virtual */ WGL_LayoutPair *
WGL_PrettyPrinter::VisitLayout(WGL_LayoutPair *p)
{
printer->OutString(p->identifier);
if (p->value != -1)
{
printer->OutString(" = ");
printer->OutInt(p->value);
}
return p;
}
/* virtual */ WGL_LayoutList *
WGL_PrettyPrinter::VisitLayoutList(WGL_LayoutList *ls)
{
BOOL first = TRUE;
// ToDo: check with grammar, might be slightly off.
for (WGL_LayoutPair *lp = ls->list.First(); lp; lp = lp->Suc())
{
if (!first)
printer->OutString(", ");
else
first = FALSE;
lp->VisitLayout(this);
}
return ls;
}
#endif // CANVAS3D_SUPPORT
|
#include<stdio.h>
main()
{
char s1[20]="abcdef";
puts(s1);
}
|
#include "EnemyAttack.h"
float EnemyAttack::BULLET_ATTACK_GAP_X = 0.002f;
float EnemyAttack::BULLET_ATTACK_GAP_Y = 0.3f;
float EnemyAttack::KNIFE_ATTACK_GAP_X_BIGGER = 0.013f - 0.002f;
float EnemyAttack::KNIFE_ATTACK_GAP_X_SMALLER = 0.013f;
float EnemyAttack::KNIFE_ATTACK_GAP_Y = 0.25f;
// Constructor
EnemyAttack::EnemyAttack(): EnemyAttack(EAttack::BLINK, Orientation::L, 0.0f, 0.0f) {}
EnemyAttack::EnemyAttack(EAttack t = BLINK, Orientation d = L, float initX = 0.0f, float initY = 0.0f) {
attack = t;
orient = d;
if (t == EAttack::BLINK) {
moveSpeed.x = 0.002f;
if (d == Orientation::L) {
mapLocation.x = initX - 0.0030;
mapLocation.y = initY + 0.2600;
}
else if (d == Orientation::R) {
mapLocation.x = initX + 0.0030;
mapLocation.y = initY + 0.2600;
}
}
action = FLY;
setScreenPosX(mapLocation.x);
setScreenPosY(mapLocation.y);
serviveTimes = 0;
}
// Distructor
EnemyAttack::~EnemyAttack() {}
bool EnemyAttack::nextFrame() {
spriteIdx++;
// Fly
if (action == Action::FLY) {
serviveTimes++;
if (attack == EAttack::BLINK) {
spriteIdx = spriteIdx % 2;
// Timeout
if (serviveTimes >= 100) {
action = Action::EXPLODE;
initSpriteIndex();
}
}
}
// Explosion
else if (action == Action::EXPLODE) {
bool isFinished = false;
if (attack == EAttack::BLINK) {
if (spriteIdx >= 6) {
isFinished = true;
initSprite();
}
}
return isFinished;
}
return false;
}
void EnemyAttack::initSprite() {
// Blink
if (attack == EAttack::BLINK) {
for (int i = 0; i < 2; i++) {
std::stringstream stream;
stream << "../media/EnemyAttack/Bullet/Fly/" << i << ".png";
std::string filename = "";
stream >> filename;
blinkFlySprite[i].Init(filename, 0);
}
// Explosion
for (int i = 0; i < 6; i++) {
std::stringstream stream;
stream << "../media/EnemyAttack/Bullet/Explosion/" << i << ".png";
std::string filename = "";
stream >> filename;
blinkExplosionSprite[i].Init(filename, 0);
}
}
}
//Blink
// Left
void EnemyAttack::blinkFlyLeft(float scenePosX) {
mapLocation.x -= moveSpeed.x;
setScreenPosX(scenePosX);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(pos), &pos);
//glBufferSubData(GL_ARRAY_BUFFER, sizeof(pos), sizeof(GL_INT) * objectCount, frame);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//Update shaders' input variable
glUseProgram(program);
glBindVertexArray(vao);
blinkFlySprite[spriteIdx].Enable();
glUniformMatrix4fv(uniforms.mv_matrix, 1, GL_FALSE, &(view * model)[0][0]);
glUniformMatrix4fv(uniforms.proj_matrix, 1, GL_FALSE, &(projection)[0][0]);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
blinkFlySprite[spriteIdx].Disable();
glBindVertexArray(0);
glUseProgram(0);
}
// Right
void EnemyAttack::blinkFlyRight(float scenePosX) {
mapLocation.x += moveSpeed.x;
setScreenPosX(scenePosX);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(pos), &pos);
//glBufferSubData(GL_ARRAY_BUFFER, sizeof(pos), sizeof(GL_INT) * objectCount, frame);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//Update shaders' input variable
glUseProgram(program);
glBindVertexArray(vao);
blinkFlySprite[spriteIdx].Enable();
glUniformMatrix4fv(uniforms.mv_matrix, 1, GL_FALSE, &(view * model)[0][0]);
glUniformMatrix4fv(uniforms.proj_matrix, 1, GL_FALSE, &(projection)[0][0]);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
blinkFlySprite[spriteIdx].Disable();
glBindVertexArray(0);
glUseProgram(0);
}
// Explosion
void EnemyAttack::bulletExplode(float scenePosX) {
setScreenPosX(scenePosX);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(pos), &pos);
//glBufferSubData(GL_ARRAY_BUFFER, sizeof(pos), sizeof(GL_INT) * objectCount, frame);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//Update shaders' input variable
glUseProgram(program);
glBindVertexArray(vao);
blinkExplosionSprite[spriteIdx].Enable();
glUniformMatrix4fv(uniforms.mv_matrix, 1, GL_FALSE, &(view * model)[0][0]);
glUniformMatrix4fv(uniforms.proj_matrix, 1, GL_FALSE, &(projection)[0][0]);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
blinkExplosionSprite[spriteIdx].Disable();
glBindVertexArray(0);
glUseProgram(0);
}
|
// Created on: 1998-07-30
// Created by: Christian CAILLET
// Copyright (c) 1998-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 _IFSelect_ParamEditor_HeaderFile
#define _IFSelect_ParamEditor_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TCollection_AsciiString.hxx>
#include <IFSelect_Editor.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_HSequenceOfHAsciiString.hxx>
class Interface_TypedValue;
class IFSelect_EditForm;
class TCollection_HAsciiString;
class Standard_Transient;
class Interface_InterfaceModel;
class IFSelect_ParamEditor;
DEFINE_STANDARD_HANDLE(IFSelect_ParamEditor, IFSelect_Editor)
//! A ParamEditor gives access for edition to a list of TypedValue
//! (i.e. of Static too)
//! Its definition is made of the TypedValue to edit themselves,
//! and can add some constants, which can then be displayed but
//! not changed (for instance, system name, processor version ...)
//!
//! I.E. it gives a way of editing or at least displaying
//! parameters as global
class IFSelect_ParamEditor : public IFSelect_Editor
{
public:
//! Creates a ParamEditor, empty, with a maximum count of params
//! (default is 100)
//! And a label, by default it will be "Param Editor"
Standard_EXPORT IFSelect_ParamEditor(const Standard_Integer nbmax = 100, const Standard_CString label = "");
//! Adds a TypedValue
//! By default, its short name equates its complete name, it can be made explicit
Standard_EXPORT void AddValue (const Handle(Interface_TypedValue)& val,
const Standard_CString shortname = "");
//! Adds a Constant Text, it will be Read Only
//! By default, its long name equates its shortname
Standard_EXPORT void AddConstantText (const Standard_CString val, const Standard_CString shortname, const Standard_CString completename = "");
Standard_EXPORT TCollection_AsciiString Label() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean Recognize (const Handle(IFSelect_EditForm)& form) const Standard_OVERRIDE;
Standard_EXPORT Handle(TCollection_HAsciiString) StringValue (const Handle(IFSelect_EditForm)& form, const Standard_Integer num) const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean Load (const Handle(IFSelect_EditForm)& form, const Handle(Standard_Transient)& ent, const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean Apply (const Handle(IFSelect_EditForm)& form, const Handle(Standard_Transient)& ent, const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE;
//! Returns a ParamEditor to work on the Static Parameters of
//! which names are listed in <list>
//! Null Handle if <list> is null or empty
Standard_EXPORT static Handle(IFSelect_ParamEditor) StaticEditor (const Handle(TColStd_HSequenceOfHAsciiString)& list, const Standard_CString label = "");
DEFINE_STANDARD_RTTIEXT(IFSelect_ParamEditor,IFSelect_Editor)
private:
TCollection_AsciiString thelabel;
};
#endif // _IFSelect_ParamEditor_HeaderFile
|
#include <SDL2/SDL.h>
#include <glad/glad.h>
#include <spdlog/spdlog.h>
#include <debug_break/debug_break.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <string>
#include <unordered_map>
#include "common/app.h"
#include "common/gl-exception.h"
#include "common/square-data.h"
std::unordered_map<std::string, int> uniformLocationCache;
int getUniformLocation(const std::string& name, unsigned int pipeline) {
if (uniformLocationCache.find(name) != uniformLocationCache.end()) {
return uniformLocationCache[name];
}
GLCall(int location = glGetUniformLocation(pipeline, name.c_str()));
if (location == -1) {
spdlog::warn("[Shader] uniform '{}' doesn't exist !", name);
debug_break();
}
uniformLocationCache[name] = location;
return location;
}
int main(int argc, char *argv[]) {
App app;
glClearColor(1, 0, 1, 1);
// ------------------ Vertex Buffer 1
unsigned int posVB;
{
GLCall(glGenBuffers(1, &posVB));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, posVB));
GLCall(glBufferData(GL_ARRAY_BUFFER, sizeof(squareData::positions), squareData::positions, GL_STATIC_DRAW));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0));
}
// ------------------ Vertex Array
unsigned int vao;
{
GLCall(glGenVertexArrays(1, &vao));
GLCall(glBindVertexArray(vao));
// Vertex input description
{
GLCall(glEnableVertexAttribArray(0));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, posVB));
GLCall(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), NULL));
}
GLCall(glBindVertexArray(0));
}
// ------------------ Index buffer
unsigned int ib;
{
GLCall(glGenBuffers(1, &ib));
GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib));
GLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(squareData::indices), squareData::indices, GL_STATIC_DRAW));
GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
}
// ------------------ Vertex shader
unsigned int vs;
int success;
char infoLog[512];
{
const char* vsSource = R"(#version 330 core
layout (location = 0) in vec3 aPos;
uniform mat4 uModel;
uniform mat4 uViewProj;
void main() {
gl_Position = uViewProj * uModel * vec4(aPos, 1.0);
}
)";
vs = glCreateShader(GL_VERTEX_SHADER);
GLCall(glShaderSource(vs, 1, &vsSource, NULL));
GLCall(glCompileShader(vs));
// Check compilation
GLCall(glGetShaderiv(vs, GL_COMPILE_STATUS, &success));
if (!success) {
GLCall(glGetShaderInfoLog(vs, 512, NULL, infoLog));
spdlog::critical("[VertexShader] Compilation failed : {}", infoLog);
debug_break();
}
}
// ------------------ Fragment shader
unsigned int fs;
{
const char* fsSource = R"(#version 330 core
out vec4 FragColor;
void main() {
FragColor = vec4(1.0f, 0.0f, 0.0f, 1.0f);
}
)";
fs = glCreateShader(GL_FRAGMENT_SHADER);
GLCall(glShaderSource(fs, 1, &fsSource, NULL));
GLCall(glCompileShader(fs));
// Check compilation
int success;
GLCall(glGetShaderiv(fs, GL_COMPILE_STATUS, &success));
if (!success) {
GLCall(glGetShaderInfoLog(fs, 512, NULL, infoLog));
spdlog::critical("[FragmentShader] Compilation failed : {}", infoLog);
debug_break();
}
}
// ------------------ Pipeline
unsigned int pipeline;
{
pipeline = glCreateProgram();
GLCall(glAttachShader(pipeline, vs));
GLCall(glAttachShader(pipeline, fs));
GLCall(glLinkProgram(pipeline));
// Check compilation
GLCall(glGetProgramiv(pipeline, GL_LINK_STATUS, &success));
if (!success) {
GLCall(glGetProgramInfoLog(pipeline, 512, NULL, infoLog));
spdlog::critical("[Pipeline] Link failed : {}", infoLog);
debug_break();
}
// Delete useless data
GLCall(glDeleteShader(vs));
GLCall(glDeleteShader(fs));
}
// ------------------ Uniforms
int modelMatUniform;
glm::mat4 modelMat = glm::mat4(1.0f);
int viewProjMatUniform;
glm::mat4 viewProjMat = glm::mat4(1.0f);
{
GLCall(glUseProgram(pipeline));
GLCall(glUniformMatrix4fv(getUniformLocation("uModel", pipeline), 1, GL_FALSE, &modelMat[0][0]));
GLCall(glUniformMatrix4fv(getUniformLocation("uViewProj", pipeline), 1, GL_FALSE, &viewProjMat[0][0]));
GLCall(glUseProgram(0));
}
float counter = 0.0f;
while (app.isRunning()) {
SDL_Event e;
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_QUIT: app.exit();
default: break;
};
}
counter += 0.05f;
if (counter > 100) {
counter = 0;
}
app.beginFrame();
// Update uniforms
GLCall(glUseProgram(pipeline));
{
modelMat = glm::rotate(glm::mat4(1.0f), counter, glm::vec3(0, 1, 0));
GLCall(glUniformMatrix4fv(getUniformLocation("uModel", pipeline), 1, GL_FALSE, &modelMat[0][0]));
}
{
glm::mat4 viewMat = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -10.0f));
glm::mat4 projMat = glm::perspective(glm::radians(45.0f), 1.0f, 0.1f, 100.0f);
viewProjMat = projMat * viewMat;
GLCall(glUniformMatrix4fv(getUniformLocation("uViewProj", pipeline), 1, GL_FALSE, &viewProjMat[0][0]));
}
// Draw call
GLCall(glBindVertexArray(vao));
GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib));
GLCall(glDrawElements(GL_TRIANGLES, std::size(squareData::indices), GL_UNSIGNED_SHORT, (void*) 0));
app.endFrame();
}
return 0;
}
|
#include "loginpage.hpp"
LoginPage::LoginPage(QWidget *parent): QVBoxLayout(parent)
{
creation = new QPushButton("Create an account !", parent);
connection = new QPushButton("Login !", parent);
QObject::connect(creation, SIGNAL(clicked()), this, SLOT(switchToCreate()));
QObject::connect(connection, SIGNAL(clicked()), this, SLOT(switchToConnect()));
QObject::connect(this, SIGNAL(login(std::string, std::string, std::string, char)), parent, SLOT(checkInputs(std::string, std::string, std::string, char)));
addWidget(creation);
addWidget(connection);
}
LoginPage::~LoginPage()
{
if (username)
username->close();
if (pswd)
pswd->close();
if (server != nullptr)
server->close();
if (_creationOK != nullptr)
_creationOK->close();
}
void LoginPage::switchToCreate()
{
_creationOK = new QPushButton("OK");
QObject::connect(_creationOK, SIGNAL(clicked()), this, SLOT(checkInputs()));
username = new QLineEdit;
pswd = new QLineEdit;
server = new QLineEdit;
QFormLayout *inputLayout = new QFormLayout;
removeWidget(connection);
removeWidget(creation);
delete connection;
delete creation;
inputLayout->addRow("Enter username:",username);
inputLayout->addRow("Enter password:",pswd);
inputLayout->addRow("Enter Server IP:",server);
addLayout(inputLayout);
addWidget(_creationOK);
input = 1;
}
void LoginPage::switchToConnect()
{
_creationOK = new QPushButton("OK");
QObject::connect(_creationOK, SIGNAL(clicked()), this, SLOT(checkInputs()));
username = new QLineEdit;
pswd = new QLineEdit;
server = new QLineEdit;
pswd->setEchoMode(QLineEdit::Password);
QFormLayout *inputLayout = new QFormLayout;
removeWidget(connection);
removeWidget(creation);
delete connection;
delete creation;
inputLayout->addRow("Enter username:",username);
inputLayout->addRow("Enter password:",pswd);
inputLayout->addRow("Enter Server IP:",server);
addLayout(inputLayout);
addWidget(_creationOK);
input = 2;
}
void LoginPage::checkInputs()
{
emit login(username->text().toStdString(), pswd->text().toStdString(), server->text().toStdString(), input);
}
|
#include <bits/stdc++.h>
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;
template<class T>inline void read(T&x){
int c;
for(c=getchar();c<32&&~c;c=getchar());
for(x=0;c>32;x=x*10+c-'0',c=getchar());
}
ll x,y,l,r;
vector<ll> xx,yy,ss;
set<ll> s;
int main () {
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
cin>>x>>y>>l>>r;
int cnt1=0,cnt2=0;
ll _r=r;
while(_r){
cnt1++;
_r/=x;
}
_r=r;
while(_r){
cnt2++;
_r/=y;
}
ll t=1;
for(int i=0;i<cnt1;i++){
xx.emplace_back(t);
t*=x;
}
t=1;
for(int i=0;i<cnt2;i++){
yy.emplace_back(t);
t*=y;
}
for(const auto &i:xx){
for(const auto &j:yy){
if(!s.count(i+j)&&(i+j)<=r&&(i+j)>=l){
ss.emplace_back(i+j);
s.insert(i+j);
}
}
}
ll ans=0;
sort(ss.begin(),ss.end());
for(int i=0;i<ss.size();i++){
// cout<<ss[i]<<endl;
if(i==0){
ans=max(ans,ss[i]-l);
}else{
ans=max(ans,ss[i]-ss[i-1]-1);
}
if(i==ss.size()-1){
ans=max(ans,r-ss[i]);
}
}
if(ss.empty()){
ans=max(ans,r-l+1);
}
cout<<ans<<endl;
return 0;
}
|
#pragma once
#include <functional>
#include <list>
#include <mutex>
using namespace std;
namespace nora {
template <typename Ret, typename... Args>
class functions {
public:
void operator()(Args... args);
typename list<function<Ret(Args...)>>::iterator add(const function<Ret(Args...)>& func);
void remove(typename list<function<Ret(Args...)>>::iterator func_id);
void clear();
private:
mutable mutex funcs_lock_;
list<function<Ret(Args...)>> funcs_;
};
template <typename Ret, typename... Args>
inline typename list<function<Ret(Args...)>>::iterator functions<Ret, Args...>::add(const function<Ret(Args...)>& func) {
lock_guard<mutex> lock(funcs_lock_);
funcs_.push_front(func);
return funcs_.begin();
}
template <typename Ret, typename... Args>
inline void functions<Ret, Args...>::operator()(Args... args) {
lock_guard<mutex> lock(funcs_lock_);
for (auto& f : funcs_) {
f(args...);
}
}
template <typename Ret, typename... Args>
inline void functions<Ret, Args...>::clear() {
lock_guard<mutex> lock(funcs_lock_);
funcs_.clear();
}
template <typename Ret, typename... Args>
inline void functions<Ret, Args...>::remove(typename list<function<Ret(Args...)>>::iterator func_id) {
lock_guard<mutex> lock(funcs_lock_);
funcs_.erase(func_id);
}
}
|
/* -*- 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.
**
*/
#ifndef DOM_LSOUTPUT
#define DOM_LSOUTPUT
#ifdef DOM3_SAVE
class ES_Object;
class DOM_Environment;
class DOM_LSOutput
{
public:
static OP_STATUS Make(ES_Object *&output, DOM_EnvironmentImpl *environment, const uni_char *systemId = NULL);
static OP_STATUS GetCharacterStream(ES_Object *&characterStream, ES_Object *output, DOM_EnvironmentImpl *environment);
static OP_STATUS GetByteStream(ES_Object *&byteStream, ES_Object *output, DOM_EnvironmentImpl *environment);
static OP_STATUS GetSystemId(const uni_char *&systemId, ES_Object *output, DOM_EnvironmentImpl *environment);
static OP_STATUS GetEncoding(const uni_char *&encoding, ES_Object *output, DOM_EnvironmentImpl *environment);
};
#endif // DOM3_SAVE
#endif // DOM_LSOUTPUT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.